repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Tools/BuildBoss/SolutionCheckerUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace BuildBoss { internal sealed class SolutionCheckerUtil : ICheckerUtil { private struct SolutionProjectData { internal ProjectEntry ProjectEntry; internal ProjectData ProjectData; internal SolutionProjectData(ProjectEntry entry, ProjectData data) { ProjectEntry = entry; ProjectData = data; } } internal string SolutionFilePath { get; } internal string SolutionPath { get; } internal bool IsPrimarySolution { get; } internal SolutionCheckerUtil(string solutionFilePath, bool isPrimarySolution) { SolutionFilePath = solutionFilePath; IsPrimarySolution = isPrimarySolution; SolutionPath = Path.GetDirectoryName(SolutionFilePath); } public bool Check(TextWriter textWriter) { var allGood = true; allGood &= CheckDuplicate(textWriter, out var map); allGood &= CheckProjects(textWriter, map); allGood &= CheckProjectSystemGuid(textWriter, map.Values); return allGood; } private bool CheckProjects(TextWriter textWriter, Dictionary<ProjectKey, SolutionProjectData> map) { var solutionMap = new Dictionary<ProjectKey, ProjectData>(); foreach (var pair in map) { solutionMap.Add(pair.Key, pair.Value.ProjectData); } var allGood = true; var count = 0; foreach (var data in map.Values.OrderBy(x => x.ProjectEntry.Name)) { var projectWriter = new StringWriter(); var projectData = data.ProjectData; projectWriter.WriteLine($"Processing {projectData.Key.FileName}"); var util = new ProjectCheckerUtil(projectData, solutionMap, IsPrimarySolution); if (!util.Check(projectWriter)) { allGood = false; textWriter.WriteLine(projectWriter.ToString()); } count++; } textWriter.WriteLine($"Processed {count} projects"); return allGood; } private bool CheckDuplicate(TextWriter textWriter, out Dictionary<ProjectKey, SolutionProjectData> map) { map = new Dictionary<ProjectKey, SolutionProjectData>(); var allGood = true; foreach (var projectEntry in SolutionUtil.ParseProjects(SolutionFilePath)) { if (projectEntry.IsFolder) { continue; } var projectFilePath = Path.Combine(SolutionPath, projectEntry.RelativeFilePath); var projectData = new ProjectData(projectFilePath); if (map.ContainsKey(projectData.Key)) { textWriter.WriteLine($"Duplicate project detected {projectData.FileName}"); allGood = false; } else { map.Add(projectData.Key, new SolutionProjectData(projectEntry, projectData)); } } return allGood; } /// <summary> /// Ensure solution files have the proper project system GUID. /// </summary> private bool CheckProjectSystemGuid(TextWriter textWriter, IEnumerable<SolutionProjectData> dataList) { Guid getExpectedGuid(ProjectData data) { var util = data.ProjectUtil; switch (ProjectEntryUtil.GetProjectFileType(data.FilePath)) { case ProjectFileType.CSharp: return ProjectEntryUtil.ManagedProjectSystemCSharp; case ProjectFileType.Basic: return ProjectEntryUtil.ManagedProjectSystemVisualBasic; case ProjectFileType.Shared: return ProjectEntryUtil.SharedProject; default: throw new Exception($"Invalid file path {data.FilePath}"); } } var allGood = true; foreach (var data in dataList.Where(x => x.ProjectEntry.ProjectType != ProjectFileType.Tool)) { var guid = getExpectedGuid(data.ProjectData); if (guid != data.ProjectEntry.TypeGuid) { var name = data.ProjectData.FileName; textWriter.WriteLine($"Project {name} should have GUID {guid} but has {data.ProjectEntry.TypeGuid}"); allGood = false; } } return allGood; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace BuildBoss { internal sealed class SolutionCheckerUtil : ICheckerUtil { private struct SolutionProjectData { internal ProjectEntry ProjectEntry; internal ProjectData ProjectData; internal SolutionProjectData(ProjectEntry entry, ProjectData data) { ProjectEntry = entry; ProjectData = data; } } internal string SolutionFilePath { get; } internal string SolutionPath { get; } internal bool IsPrimarySolution { get; } internal SolutionCheckerUtil(string solutionFilePath, bool isPrimarySolution) { SolutionFilePath = solutionFilePath; IsPrimarySolution = isPrimarySolution; SolutionPath = Path.GetDirectoryName(SolutionFilePath); } public bool Check(TextWriter textWriter) { var allGood = true; allGood &= CheckDuplicate(textWriter, out var map); allGood &= CheckProjects(textWriter, map); allGood &= CheckProjectSystemGuid(textWriter, map.Values); return allGood; } private bool CheckProjects(TextWriter textWriter, Dictionary<ProjectKey, SolutionProjectData> map) { var solutionMap = new Dictionary<ProjectKey, ProjectData>(); foreach (var pair in map) { solutionMap.Add(pair.Key, pair.Value.ProjectData); } var allGood = true; var count = 0; foreach (var data in map.Values.OrderBy(x => x.ProjectEntry.Name)) { var projectWriter = new StringWriter(); var projectData = data.ProjectData; projectWriter.WriteLine($"Processing {projectData.Key.FileName}"); var util = new ProjectCheckerUtil(projectData, solutionMap, IsPrimarySolution); if (!util.Check(projectWriter)) { allGood = false; textWriter.WriteLine(projectWriter.ToString()); } count++; } textWriter.WriteLine($"Processed {count} projects"); return allGood; } private bool CheckDuplicate(TextWriter textWriter, out Dictionary<ProjectKey, SolutionProjectData> map) { map = new Dictionary<ProjectKey, SolutionProjectData>(); var allGood = true; foreach (var projectEntry in SolutionUtil.ParseProjects(SolutionFilePath)) { if (projectEntry.IsFolder) { continue; } var projectFilePath = Path.Combine(SolutionPath, projectEntry.RelativeFilePath); var projectData = new ProjectData(projectFilePath); if (map.ContainsKey(projectData.Key)) { textWriter.WriteLine($"Duplicate project detected {projectData.FileName}"); allGood = false; } else { map.Add(projectData.Key, new SolutionProjectData(projectEntry, projectData)); } } return allGood; } /// <summary> /// Ensure solution files have the proper project system GUID. /// </summary> private bool CheckProjectSystemGuid(TextWriter textWriter, IEnumerable<SolutionProjectData> dataList) { Guid getExpectedGuid(ProjectData data) { var util = data.ProjectUtil; switch (ProjectEntryUtil.GetProjectFileType(data.FilePath)) { case ProjectFileType.CSharp: return ProjectEntryUtil.ManagedProjectSystemCSharp; case ProjectFileType.Basic: return ProjectEntryUtil.ManagedProjectSystemVisualBasic; case ProjectFileType.Shared: return ProjectEntryUtil.SharedProject; default: throw new Exception($"Invalid file path {data.FilePath}"); } } var allGood = true; foreach (var data in dataList.Where(x => x.ProjectEntry.ProjectType != ProjectFileType.Tool)) { var guid = getExpectedGuid(data.ProjectData); if (guid != data.ProjectEntry.TypeGuid) { var name = data.ProjectData.FileName; textWriter.WriteLine($"Project {name} should have GUID {guid} but has {data.ProjectEntry.TypeGuid}"); allGood = false; } } return allGood; } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Workspaces/CSharp/Portable/Recommendations/CSharpRecommendationServiceRunner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Recommendations { internal partial class CSharpRecommendationServiceRunner : AbstractRecommendationServiceRunner<CSharpSyntaxContext> { public CSharpRecommendationServiceRunner( CSharpSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken) : base(context, filterOutOfScopeLocals, cancellationToken) { } public override RecommendedSymbols GetRecommendedSymbols() { if (_context.IsInNonUserCode || _context.IsPreProcessorDirectiveContext) { return default; } if (!_context.IsRightOfNameSeparator) return new RecommendedSymbols(GetSymbolsForCurrentContext()); return GetSymbolsOffOfContainer(); } public override bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(true)] out ITypeSymbol? explicitLambdaParameterType) { if (lambdaSyntax.IsKind<ParenthesizedLambdaExpressionSyntax>(SyntaxKind.ParenthesizedLambdaExpression, out var parenthesizedLambdaSyntax)) { var parameters = parenthesizedLambdaSyntax.ParameterList.Parameters; if (parameters.Count > ordinalInLambda) { var parameter = parameters[ordinalInLambda]; if (parameter.Type != null) { explicitLambdaParameterType = _context.SemanticModel.GetTypeInfo(parameter.Type, _cancellationToken).Type; return explicitLambdaParameterType != null; } } } // Non-parenthesized lambdas cannot explicitly specify the type of the single parameter explicitLambdaParameterType = null; return false; } private ImmutableArray<ISymbol> GetSymbolsForCurrentContext() { if (_context.IsGlobalStatementContext) { // Script and interactive return GetSymbolsForGlobalStatementContext(); } else if (_context.IsAnyExpressionContext || _context.IsStatementContext || _context.SyntaxTree.IsDefiniteCastTypeContext(_context.Position, _context.LeftToken)) { // GitHub #717: With automatic brace completion active, typing '(i' produces "(i)", which gets parsed as // as cast. The user might be trying to type a parenthesized expression, so even though a cast // is a type-only context, we'll show all symbols anyway. return GetSymbolsForExpressionOrStatementContext(); } else if (_context.IsTypeContext || _context.IsNamespaceContext) { return GetSymbolsForTypeOrNamespaceContext(); } else if (_context.IsLabelContext) { return GetSymbolsForLabelContext(); } else if (_context.IsTypeArgumentOfConstraintContext) { return GetSymbolsForTypeArgumentOfConstraintClause(); } else if (_context.IsDestructorTypeContext) { var symbol = _context.SemanticModel.GetDeclaredSymbol(_context.ContainingTypeOrEnumDeclaration!, _cancellationToken); return symbol == null ? ImmutableArray<ISymbol>.Empty : ImmutableArray.Create<ISymbol>(symbol); } else if (_context.IsNamespaceDeclarationNameContext) { return GetSymbolsForNamespaceDeclarationNameContext<BaseNamespaceDeclarationSyntax>(); } return ImmutableArray<ISymbol>.Empty; } private RecommendedSymbols GetSymbolsOffOfContainer() { // Ensure that we have the correct token in A.B| case var node = _context.TargetToken.GetRequiredParent(); return node switch { MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAccessExpression) memberAccess => GetSymbolsOffOfExpression(memberAccess.Expression), MemberAccessExpressionSyntax(SyntaxKind.PointerMemberAccessExpression) memberAccess => GetSymbolsOffOfDereferencedExpression(memberAccess.Expression), // This code should be executing only if the cursor is between two dots in a dotdot token. RangeExpressionSyntax rangeExpression => GetSymbolsOffOfExpression(rangeExpression.LeftOperand), QualifiedNameSyntax qualifiedName => GetSymbolsOffOfName(qualifiedName.Left), AliasQualifiedNameSyntax aliasName => GetSymbolsOffOffAlias(aliasName.Alias), MemberBindingExpressionSyntax _ => GetSymbolsOffOfConditionalReceiver(node.GetParentConditionalAccessExpression()!.Expression), _ => default, }; } private ImmutableArray<ISymbol> GetSymbolsForGlobalStatementContext() { var syntaxTree = _context.SyntaxTree; var position = _context.Position; var token = _context.LeftToken; // The following code is a hack to get around a binding problem when asking binding // questions immediately after a using directive. This is special-cased in the binder // factory to ensure that using directives are not within scope inside other using // directives. That generally works fine for .cs, but it's a problem for interactive // code in this case: // // using System; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.UsingDirective) && position >= token.Span.End) { var compUnit = (CompilationUnitSyntax)syntaxTree.GetRoot(_cancellationToken); if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken() == token) { token = token.GetNextToken(includeZeroWidth: true); } } var symbols = _context.SemanticModel.LookupSymbols(token.SpanStart); return symbols; } private ImmutableArray<ISymbol> GetSymbolsForTypeArgumentOfConstraintClause() { var enclosingSymbol = _context.LeftToken.GetRequiredParent() .AncestorsAndSelf() .Select(n => _context.SemanticModel.GetDeclaredSymbol(n, _cancellationToken)) .WhereNotNull() .FirstOrDefault(); var symbols = enclosingSymbol != null ? enclosingSymbol.GetTypeArguments() : ImmutableArray<ITypeSymbol>.Empty; return ImmutableArray<ISymbol>.CastUp(symbols); } private RecommendedSymbols GetSymbolsOffOffAlias(IdentifierNameSyntax alias) { var aliasSymbol = _context.SemanticModel.GetAliasInfo(alias, _cancellationToken); if (aliasSymbol == null) return default; return new RecommendedSymbols(_context.SemanticModel.LookupNamespacesAndTypes( alias.SpanStart, aliasSymbol.Target)); } private ImmutableArray<ISymbol> GetSymbolsForLabelContext() { var allLabels = _context.SemanticModel.LookupLabels(_context.LeftToken.SpanStart); // Exclude labels (other than 'default') that come from case switch statements return allLabels .WhereAsArray(label => label.DeclaringSyntaxReferences.First().GetSyntax(_cancellationToken) .IsKind(SyntaxKind.LabeledStatement, SyntaxKind.DefaultSwitchLabel)); } private ImmutableArray<ISymbol> GetSymbolsForTypeOrNamespaceContext() { var symbols = _context.SemanticModel.LookupNamespacesAndTypes(_context.LeftToken.SpanStart); if (_context.TargetToken.IsUsingKeywordInUsingDirective()) { return symbols.WhereAsArray(s => s.IsNamespace()); } if (_context.TargetToken.IsStaticKeywordInUsingDirective()) { return symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()); } return symbols; } private ImmutableArray<ISymbol> GetSymbolsForExpressionOrStatementContext() { // Check if we're in an interesting situation like this: // // i // <-- here // I = 0; // The problem is that "i I = 0" causes a local to be in scope called "I". So, later when // we look up symbols, it masks any other 'I's in scope (i.e. if there's a field with that // name). If this is the case, we do not want to filter out inaccessible locals. var filterOutOfScopeLocals = _filterOutOfScopeLocals; if (filterOutOfScopeLocals) filterOutOfScopeLocals = !_context.LeftToken.GetRequiredParent().IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type); var symbols = !_context.IsNameOfContext && _context.LeftToken.GetRequiredParent().IsInStaticContext() ? _context.SemanticModel.LookupStaticMembers(_context.LeftToken.SpanStart) : _context.SemanticModel.LookupSymbols(_context.LeftToken.SpanStart); // Filter out any extension methods that might be imported by a using static directive. // But include extension methods declared in the context's type or it's parents var contextOuterTypes = _context.GetOuterTypes(_cancellationToken); var contextEnclosingNamedType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); symbols = symbols.WhereAsArray(symbol => !symbol.IsExtensionMethod() || Equals(contextEnclosingNamedType, symbol.ContainingType) || contextOuterTypes.Any(outerType => outerType.Equals(symbol.ContainingType))); // The symbols may include local variables that are declared later in the method and // should not be included in the completion list, so remove those. Filter them away, // unless we're in the debugger, where we show all locals in scope. if (filterOutOfScopeLocals) { symbols = symbols.WhereAsArray(symbol => !symbol.IsInaccessibleLocal(_context.Position)); } return symbols; } private RecommendedSymbols GetSymbolsOffOfName(NameSyntax name) { // Using an is pattern on an enum is a qualified name, but normal symbol processing works fine if (_context.IsEnumTypeMemberAccessContext) return GetSymbolsOffOfExpression(name); if (ShouldBeTreatedAsTypeInsteadOfExpression(name, out var nameBinding, out var container)) return GetSymbolsOffOfBoundExpression(name, name, nameBinding, container, unwrapNullable: false); // We're in a name-only context, since if we were an expression we'd be a // MemberAccessExpressionSyntax. Thus, let's do other namespaces and types. nameBinding = _context.SemanticModel.GetSymbolInfo(name, _cancellationToken); if (nameBinding.Symbol is not INamespaceOrTypeSymbol symbol) return default; if (_context.IsNameOfContext) return new RecommendedSymbols(_context.SemanticModel.LookupSymbols(position: name.SpanStart, container: symbol)); var symbols = _context.SemanticModel.LookupNamespacesAndTypes( position: name.SpanStart, container: symbol); if (_context.IsNamespaceDeclarationNameContext) { var declarationSyntax = name.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); return new RecommendedSymbols(symbols.WhereAsArray(s => IsNonIntersectingNamespace(s, declarationSyntax))); } // Filter the types when in a using directive, but not an alias. // // Cases: // using | -- Show namespaces // using A.| -- Show namespaces // using static | -- Show namespace and types // using A = B.| -- Show namespace and types var usingDirective = name.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null && usingDirective.Alias == null) { return new RecommendedSymbols(usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) ? symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()) : symbols.WhereAsArray(s => s.IsNamespace())); } return new RecommendedSymbols(symbols); } /// <summary> /// DeterminesCheck if we're in an interesting situation like this: /// <code> /// int i = 5; /// i. // -- here /// List ml = new List(); /// </code> /// The problem is that "i.List" gets parsed as a type. In this case we need to try binding again as if "i" is /// an expression and not a type. In order to do that, we need to speculate as to what 'i' meant if it wasn't /// part of a local declaration's type. /// <para/> /// Another interesting case is something like: /// <code> /// stringList. /// await Test2(); /// </code> /// Here "stringList.await" is thought of as the return type of a local function. /// </summary> private bool ShouldBeTreatedAsTypeInsteadOfExpression( ExpressionSyntax name, out SymbolInfo leftHandBinding, out ITypeSymbol? container) { if (name.IsFoundUnder<LocalFunctionStatementSyntax>(d => d.ReturnType) || name.IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type) || name.IsFoundUnder<FieldDeclarationSyntax>(d => d.Declaration.Type)) { leftHandBinding = _context.SemanticModel.GetSpeculativeSymbolInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression); container = _context.SemanticModel.GetSpeculativeTypeInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression).Type; return true; } leftHandBinding = default; container = null; return false; } private RecommendedSymbols GetSymbolsOffOfExpression(ExpressionSyntax? originalExpression) { if (originalExpression == null) return default; // In case of 'await x$$', we want to move to 'x' to get it's members. // To run GetSymbolInfo, we also need to get rid of parenthesis. var expression = originalExpression is AwaitExpressionSyntax awaitExpression ? awaitExpression.Expression.WalkDownParentheses() : originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; var result = GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); // Check for the Color Color case. if (originalExpression.CanAccessInstanceAndStaticMembersOffOf(_context.SemanticModel, _cancellationToken)) { var speculativeSymbolInfo = _context.SemanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace); var typeMembers = GetSymbolsOffOfBoundExpression(originalExpression, expression, speculativeSymbolInfo, container, unwrapNullable: false); result = new RecommendedSymbols( result.NamedSymbols.Concat(typeMembers.NamedSymbols), result.UnnamedSymbols); } return result; } private RecommendedSymbols GetSymbolsOffOfDereferencedExpression(ExpressionSyntax originalExpression) { var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; if (container is IPointerTypeSymbol pointerType) { container = pointerType.PointedAtType; } return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); } private RecommendedSymbols GetSymbolsOffOfConditionalReceiver(ExpressionSyntax originalExpression) { // Given ((T?)t)?.|, the '.' will behave as if the expression was actually ((T)t).|. More plainly, // a member access off of a conditional receiver of nullable type binds to the unwrapped nullable // type. This is not exposed via the binding information for the LHS, so repeat this work here. var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; // If the thing on the left is a type, namespace, or alias, we shouldn't show anything in // IntelliSense. if (leftHandBinding.GetBestOrAllSymbols().FirstOrDefault().MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias)) return default; return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: true); } private RecommendedSymbols GetSymbolsOffOfBoundExpression( ExpressionSyntax originalExpression, ExpressionSyntax expression, SymbolInfo leftHandBinding, ITypeSymbol? containerType, bool unwrapNullable) { var abstractsOnly = false; var excludeInstance = false; var excludeStatic = true; ISymbol? containerSymbol = containerType; var symbol = leftHandBinding.GetAnySymbol(); if (symbol != null) { // If the thing on the left is a lambda expression, we shouldn't show anything. if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction }) return default; var originalExpressionKind = originalExpression.Kind(); // If the thing on the left is a type, namespace or alias and the original // expression was parenthesized, we shouldn't show anything in IntelliSense. if (originalExpressionKind is SyntaxKind.ParenthesizedExpression && symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.Alias) { return default; } // If the thing on the left is a method name identifier, we shouldn't show anything. if (symbol.Kind is SymbolKind.Method && originalExpressionKind is SyntaxKind.IdentifierName or SyntaxKind.GenericName) { return default; } // If the thing on the left is an event that can't be used as a field, we shouldn't show anything if (symbol is IEventSymbol ev && !_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, ev)) { return default; } if (symbol is IAliasSymbol alias) symbol = alias.Target; if (symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.TypeParameter) { // For named typed, namespaces, and type parameters (potentially constrainted to interface with statics), we flip things around. // We only want statics and not instance members. excludeInstance = true; excludeStatic = false; abstractsOnly = symbol.Kind == SymbolKind.TypeParameter; containerSymbol = symbol; } // Special case parameters. If we have a normal (non this/base) parameter, then that's what we want to // lookup symbols off of as we have a lot of special logic for determining member symbols of lambda // parameters. // // If it is a this/base parameter and we're in a static context, we shouldn't show anything if (symbol is IParameterSymbol parameter) { if (parameter.IsThis && expression.IsInStaticContext()) return default; containerSymbol = symbol; } } else if (containerType != null) { // Otherwise, if it wasn't a symbol on the left, but it was something that had a type, // then include instance members for it. excludeStatic = true; } if (containerSymbol == null) return default; Debug.Assert(!excludeInstance || !excludeStatic); Debug.Assert(!abstractsOnly || (abstractsOnly && !excludeStatic && excludeInstance)); // nameof(X.| // Show static and instance members. if (_context.IsNameOfContext) { excludeInstance = false; excludeStatic = false; } var useBaseReferenceAccessibility = symbol is IParameterSymbol { IsThis: true } p && !p.Type.Equals(containerType); var symbols = GetMemberSymbols(containerSymbol, position: originalExpression.SpanStart, excludeInstance, useBaseReferenceAccessibility, unwrapNullable); // If we're showing instance members, don't include nested types var namedSymbols = excludeStatic ? symbols.WhereAsArray(s => !(s.IsStatic || s is ITypeSymbol)) : (abstractsOnly ? symbols.WhereAsArray(s => s.IsAbstract) : symbols); // if we're dotting off an instance, then add potential operators/indexers/conversions that may be // applicable to it as well. var unnamedSymbols = _context.IsNameOfContext || excludeInstance ? default : GetUnnamedSymbols(originalExpression); return new RecommendedSymbols(namedSymbols, unnamedSymbols); } private ImmutableArray<ISymbol> GetUnnamedSymbols(ExpressionSyntax originalExpression) { var semanticModel = _context.SemanticModel; var container = GetContainerForUnnamedSymbols(semanticModel, originalExpression); if (container == null) return ImmutableArray<ISymbol>.Empty; // In a case like `x?.Y` if we bind the type of `.Y` we will get a value type back (like `int`), and not // `int?`. However, we want to think of the constructed type as that's the type of the overall expression // that will be casted. if (originalExpression.GetRootConditionalAccessExpression() != null) container = TryMakeNullable(semanticModel.Compilation, container); using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols); AddIndexers(container, symbols); AddOperators(container, symbols); AddConversions(container, symbols); return symbols.ToImmutable(); } private ITypeSymbol? GetContainerForUnnamedSymbols(SemanticModel semanticModel, ExpressionSyntax originalExpression) { return ShouldBeTreatedAsTypeInsteadOfExpression(originalExpression, out _, out var container) ? container : semanticModel.GetTypeInfo(originalExpression, _cancellationToken).Type; } private void AddIndexers(ITypeSymbol container, ArrayBuilder<ISymbol> symbols) { var containingType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); if (containingType == null) return; foreach (var member in container.RemoveNullableIfPresent().GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType)) { if (member.IsIndexer) symbols.Add(member); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Recommendations { internal partial class CSharpRecommendationServiceRunner : AbstractRecommendationServiceRunner<CSharpSyntaxContext> { public CSharpRecommendationServiceRunner( CSharpSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken) : base(context, filterOutOfScopeLocals, cancellationToken) { } public override RecommendedSymbols GetRecommendedSymbols() { if (_context.IsInNonUserCode || _context.IsPreProcessorDirectiveContext) { return default; } if (!_context.IsRightOfNameSeparator) return new RecommendedSymbols(GetSymbolsForCurrentContext()); return GetSymbolsOffOfContainer(); } public override bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(true)] out ITypeSymbol? explicitLambdaParameterType) { if (lambdaSyntax.IsKind<ParenthesizedLambdaExpressionSyntax>(SyntaxKind.ParenthesizedLambdaExpression, out var parenthesizedLambdaSyntax)) { var parameters = parenthesizedLambdaSyntax.ParameterList.Parameters; if (parameters.Count > ordinalInLambda) { var parameter = parameters[ordinalInLambda]; if (parameter.Type != null) { explicitLambdaParameterType = _context.SemanticModel.GetTypeInfo(parameter.Type, _cancellationToken).Type; return explicitLambdaParameterType != null; } } } // Non-parenthesized lambdas cannot explicitly specify the type of the single parameter explicitLambdaParameterType = null; return false; } private ImmutableArray<ISymbol> GetSymbolsForCurrentContext() { if (_context.IsGlobalStatementContext) { // Script and interactive return GetSymbolsForGlobalStatementContext(); } else if (_context.IsAnyExpressionContext || _context.IsStatementContext || _context.SyntaxTree.IsDefiniteCastTypeContext(_context.Position, _context.LeftToken)) { // GitHub #717: With automatic brace completion active, typing '(i' produces "(i)", which gets parsed as // as cast. The user might be trying to type a parenthesized expression, so even though a cast // is a type-only context, we'll show all symbols anyway. return GetSymbolsForExpressionOrStatementContext(); } else if (_context.IsTypeContext || _context.IsNamespaceContext) { return GetSymbolsForTypeOrNamespaceContext(); } else if (_context.IsLabelContext) { return GetSymbolsForLabelContext(); } else if (_context.IsTypeArgumentOfConstraintContext) { return GetSymbolsForTypeArgumentOfConstraintClause(); } else if (_context.IsDestructorTypeContext) { var symbol = _context.SemanticModel.GetDeclaredSymbol(_context.ContainingTypeOrEnumDeclaration!, _cancellationToken); return symbol == null ? ImmutableArray<ISymbol>.Empty : ImmutableArray.Create<ISymbol>(symbol); } else if (_context.IsNamespaceDeclarationNameContext) { return GetSymbolsForNamespaceDeclarationNameContext<BaseNamespaceDeclarationSyntax>(); } return ImmutableArray<ISymbol>.Empty; } private RecommendedSymbols GetSymbolsOffOfContainer() { // Ensure that we have the correct token in A.B| case var node = _context.TargetToken.GetRequiredParent(); return node switch { MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAccessExpression) memberAccess => GetSymbolsOffOfExpression(memberAccess.Expression), MemberAccessExpressionSyntax(SyntaxKind.PointerMemberAccessExpression) memberAccess => GetSymbolsOffOfDereferencedExpression(memberAccess.Expression), // This code should be executing only if the cursor is between two dots in a dotdot token. RangeExpressionSyntax rangeExpression => GetSymbolsOffOfExpression(rangeExpression.LeftOperand), QualifiedNameSyntax qualifiedName => GetSymbolsOffOfName(qualifiedName.Left), AliasQualifiedNameSyntax aliasName => GetSymbolsOffOffAlias(aliasName.Alias), MemberBindingExpressionSyntax _ => GetSymbolsOffOfConditionalReceiver(node.GetParentConditionalAccessExpression()!.Expression), _ => default, }; } private ImmutableArray<ISymbol> GetSymbolsForGlobalStatementContext() { var syntaxTree = _context.SyntaxTree; var position = _context.Position; var token = _context.LeftToken; // The following code is a hack to get around a binding problem when asking binding // questions immediately after a using directive. This is special-cased in the binder // factory to ensure that using directives are not within scope inside other using // directives. That generally works fine for .cs, but it's a problem for interactive // code in this case: // // using System; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.UsingDirective) && position >= token.Span.End) { var compUnit = (CompilationUnitSyntax)syntaxTree.GetRoot(_cancellationToken); if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken() == token) { token = token.GetNextToken(includeZeroWidth: true); } } var symbols = _context.SemanticModel.LookupSymbols(token.SpanStart); return symbols; } private ImmutableArray<ISymbol> GetSymbolsForTypeArgumentOfConstraintClause() { var enclosingSymbol = _context.LeftToken.GetRequiredParent() .AncestorsAndSelf() .Select(n => _context.SemanticModel.GetDeclaredSymbol(n, _cancellationToken)) .WhereNotNull() .FirstOrDefault(); var symbols = enclosingSymbol != null ? enclosingSymbol.GetTypeArguments() : ImmutableArray<ITypeSymbol>.Empty; return ImmutableArray<ISymbol>.CastUp(symbols); } private RecommendedSymbols GetSymbolsOffOffAlias(IdentifierNameSyntax alias) { var aliasSymbol = _context.SemanticModel.GetAliasInfo(alias, _cancellationToken); if (aliasSymbol == null) return default; return new RecommendedSymbols(_context.SemanticModel.LookupNamespacesAndTypes( alias.SpanStart, aliasSymbol.Target)); } private ImmutableArray<ISymbol> GetSymbolsForLabelContext() { var allLabels = _context.SemanticModel.LookupLabels(_context.LeftToken.SpanStart); // Exclude labels (other than 'default') that come from case switch statements return allLabels .WhereAsArray(label => label.DeclaringSyntaxReferences.First().GetSyntax(_cancellationToken) .IsKind(SyntaxKind.LabeledStatement, SyntaxKind.DefaultSwitchLabel)); } private ImmutableArray<ISymbol> GetSymbolsForTypeOrNamespaceContext() { var symbols = _context.SemanticModel.LookupNamespacesAndTypes(_context.LeftToken.SpanStart); if (_context.TargetToken.IsUsingKeywordInUsingDirective()) { return symbols.WhereAsArray(s => s.IsNamespace()); } if (_context.TargetToken.IsStaticKeywordInUsingDirective()) { return symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()); } return symbols; } private ImmutableArray<ISymbol> GetSymbolsForExpressionOrStatementContext() { // Check if we're in an interesting situation like this: // // i // <-- here // I = 0; // The problem is that "i I = 0" causes a local to be in scope called "I". So, later when // we look up symbols, it masks any other 'I's in scope (i.e. if there's a field with that // name). If this is the case, we do not want to filter out inaccessible locals. var filterOutOfScopeLocals = _filterOutOfScopeLocals; if (filterOutOfScopeLocals) filterOutOfScopeLocals = !_context.LeftToken.GetRequiredParent().IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type); var symbols = !_context.IsNameOfContext && _context.LeftToken.GetRequiredParent().IsInStaticContext() ? _context.SemanticModel.LookupStaticMembers(_context.LeftToken.SpanStart) : _context.SemanticModel.LookupSymbols(_context.LeftToken.SpanStart); // Filter out any extension methods that might be imported by a using static directive. // But include extension methods declared in the context's type or it's parents var contextOuterTypes = _context.GetOuterTypes(_cancellationToken); var contextEnclosingNamedType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); symbols = symbols.WhereAsArray(symbol => !symbol.IsExtensionMethod() || Equals(contextEnclosingNamedType, symbol.ContainingType) || contextOuterTypes.Any(outerType => outerType.Equals(symbol.ContainingType))); // The symbols may include local variables that are declared later in the method and // should not be included in the completion list, so remove those. Filter them away, // unless we're in the debugger, where we show all locals in scope. if (filterOutOfScopeLocals) { symbols = symbols.WhereAsArray(symbol => !symbol.IsInaccessibleLocal(_context.Position)); } return symbols; } private RecommendedSymbols GetSymbolsOffOfName(NameSyntax name) { // Using an is pattern on an enum is a qualified name, but normal symbol processing works fine if (_context.IsEnumTypeMemberAccessContext) return GetSymbolsOffOfExpression(name); if (ShouldBeTreatedAsTypeInsteadOfExpression(name, out var nameBinding, out var container)) return GetSymbolsOffOfBoundExpression(name, name, nameBinding, container, unwrapNullable: false); // We're in a name-only context, since if we were an expression we'd be a // MemberAccessExpressionSyntax. Thus, let's do other namespaces and types. nameBinding = _context.SemanticModel.GetSymbolInfo(name, _cancellationToken); if (nameBinding.Symbol is not INamespaceOrTypeSymbol symbol) return default; if (_context.IsNameOfContext) return new RecommendedSymbols(_context.SemanticModel.LookupSymbols(position: name.SpanStart, container: symbol)); var symbols = _context.SemanticModel.LookupNamespacesAndTypes( position: name.SpanStart, container: symbol); if (_context.IsNamespaceDeclarationNameContext) { var declarationSyntax = name.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); return new RecommendedSymbols(symbols.WhereAsArray(s => IsNonIntersectingNamespace(s, declarationSyntax))); } // Filter the types when in a using directive, but not an alias. // // Cases: // using | -- Show namespaces // using A.| -- Show namespaces // using static | -- Show namespace and types // using A = B.| -- Show namespace and types var usingDirective = name.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null && usingDirective.Alias == null) { return new RecommendedSymbols(usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) ? symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()) : symbols.WhereAsArray(s => s.IsNamespace())); } return new RecommendedSymbols(symbols); } /// <summary> /// DeterminesCheck if we're in an interesting situation like this: /// <code> /// int i = 5; /// i. // -- here /// List ml = new List(); /// </code> /// The problem is that "i.List" gets parsed as a type. In this case we need to try binding again as if "i" is /// an expression and not a type. In order to do that, we need to speculate as to what 'i' meant if it wasn't /// part of a local declaration's type. /// <para/> /// Another interesting case is something like: /// <code> /// stringList. /// await Test2(); /// </code> /// Here "stringList.await" is thought of as the return type of a local function. /// </summary> private bool ShouldBeTreatedAsTypeInsteadOfExpression( ExpressionSyntax name, out SymbolInfo leftHandBinding, out ITypeSymbol? container) { if (name.IsFoundUnder<LocalFunctionStatementSyntax>(d => d.ReturnType) || name.IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type) || name.IsFoundUnder<FieldDeclarationSyntax>(d => d.Declaration.Type)) { leftHandBinding = _context.SemanticModel.GetSpeculativeSymbolInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression); container = _context.SemanticModel.GetSpeculativeTypeInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression).Type; return true; } leftHandBinding = default; container = null; return false; } private RecommendedSymbols GetSymbolsOffOfExpression(ExpressionSyntax? originalExpression) { if (originalExpression == null) return default; // In case of 'await x$$', we want to move to 'x' to get it's members. // To run GetSymbolInfo, we also need to get rid of parenthesis. var expression = originalExpression is AwaitExpressionSyntax awaitExpression ? awaitExpression.Expression.WalkDownParentheses() : originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; var result = GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); // Check for the Color Color case. if (originalExpression.CanAccessInstanceAndStaticMembersOffOf(_context.SemanticModel, _cancellationToken)) { var speculativeSymbolInfo = _context.SemanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace); var typeMembers = GetSymbolsOffOfBoundExpression(originalExpression, expression, speculativeSymbolInfo, container, unwrapNullable: false); result = new RecommendedSymbols( result.NamedSymbols.Concat(typeMembers.NamedSymbols), result.UnnamedSymbols); } return result; } private RecommendedSymbols GetSymbolsOffOfDereferencedExpression(ExpressionSyntax originalExpression) { var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; if (container is IPointerTypeSymbol pointerType) { container = pointerType.PointedAtType; } return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); } private RecommendedSymbols GetSymbolsOffOfConditionalReceiver(ExpressionSyntax originalExpression) { // Given ((T?)t)?.|, the '.' will behave as if the expression was actually ((T)t).|. More plainly, // a member access off of a conditional receiver of nullable type binds to the unwrapped nullable // type. This is not exposed via the binding information for the LHS, so repeat this work here. var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; // If the thing on the left is a type, namespace, or alias, we shouldn't show anything in // IntelliSense. if (leftHandBinding.GetBestOrAllSymbols().FirstOrDefault().MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias)) return default; return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: true); } private RecommendedSymbols GetSymbolsOffOfBoundExpression( ExpressionSyntax originalExpression, ExpressionSyntax expression, SymbolInfo leftHandBinding, ITypeSymbol? containerType, bool unwrapNullable) { var abstractsOnly = false; var excludeInstance = false; var excludeStatic = true; ISymbol? containerSymbol = containerType; var symbol = leftHandBinding.GetAnySymbol(); if (symbol != null) { // If the thing on the left is a lambda expression, we shouldn't show anything. if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction }) return default; var originalExpressionKind = originalExpression.Kind(); // If the thing on the left is a type, namespace or alias and the original // expression was parenthesized, we shouldn't show anything in IntelliSense. if (originalExpressionKind is SyntaxKind.ParenthesizedExpression && symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.Alias) { return default; } // If the thing on the left is a method name identifier, we shouldn't show anything. if (symbol.Kind is SymbolKind.Method && originalExpressionKind is SyntaxKind.IdentifierName or SyntaxKind.GenericName) { return default; } // If the thing on the left is an event that can't be used as a field, we shouldn't show anything if (symbol is IEventSymbol ev && !_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, ev)) { return default; } if (symbol is IAliasSymbol alias) symbol = alias.Target; if (symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.TypeParameter) { // For named typed, namespaces, and type parameters (potentially constrainted to interface with statics), we flip things around. // We only want statics and not instance members. excludeInstance = true; excludeStatic = false; abstractsOnly = symbol.Kind == SymbolKind.TypeParameter; containerSymbol = symbol; } // Special case parameters. If we have a normal (non this/base) parameter, then that's what we want to // lookup symbols off of as we have a lot of special logic for determining member symbols of lambda // parameters. // // If it is a this/base parameter and we're in a static context, we shouldn't show anything if (symbol is IParameterSymbol parameter) { if (parameter.IsThis && expression.IsInStaticContext()) return default; containerSymbol = symbol; } } else if (containerType != null) { // Otherwise, if it wasn't a symbol on the left, but it was something that had a type, // then include instance members for it. excludeStatic = true; } if (containerSymbol == null) return default; Debug.Assert(!excludeInstance || !excludeStatic); Debug.Assert(!abstractsOnly || (abstractsOnly && !excludeStatic && excludeInstance)); // nameof(X.| // Show static and instance members. if (_context.IsNameOfContext) { excludeInstance = false; excludeStatic = false; } var useBaseReferenceAccessibility = symbol is IParameterSymbol { IsThis: true } p && !p.Type.Equals(containerType); var symbols = GetMemberSymbols(containerSymbol, position: originalExpression.SpanStart, excludeInstance, useBaseReferenceAccessibility, unwrapNullable); // If we're showing instance members, don't include nested types var namedSymbols = excludeStatic ? symbols.WhereAsArray(s => !(s.IsStatic || s is ITypeSymbol)) : (abstractsOnly ? symbols.WhereAsArray(s => s.IsAbstract) : symbols); // if we're dotting off an instance, then add potential operators/indexers/conversions that may be // applicable to it as well. var unnamedSymbols = _context.IsNameOfContext || excludeInstance ? default : GetUnnamedSymbols(originalExpression); return new RecommendedSymbols(namedSymbols, unnamedSymbols); } private ImmutableArray<ISymbol> GetUnnamedSymbols(ExpressionSyntax originalExpression) { var semanticModel = _context.SemanticModel; var container = GetContainerForUnnamedSymbols(semanticModel, originalExpression); if (container == null) return ImmutableArray<ISymbol>.Empty; // In a case like `x?.Y` if we bind the type of `.Y` we will get a value type back (like `int`), and not // `int?`. However, we want to think of the constructed type as that's the type of the overall expression // that will be casted. if (originalExpression.GetRootConditionalAccessExpression() != null) container = TryMakeNullable(semanticModel.Compilation, container); using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols); AddIndexers(container, symbols); AddOperators(container, symbols); AddConversions(container, symbols); return symbols.ToImmutable(); } private ITypeSymbol? GetContainerForUnnamedSymbols(SemanticModel semanticModel, ExpressionSyntax originalExpression) { return ShouldBeTreatedAsTypeInsteadOfExpression(originalExpression, out _, out var container) ? container : semanticModel.GetTypeInfo(originalExpression, _cancellationToken).Type; } private void AddIndexers(ITypeSymbol container, ArrayBuilder<ISymbol> symbols) { var containingType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); if (containingType == null) return; foreach (var member in container.RemoveNullableIfPresent().GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType)) { if (member.IsIndexer) symbols.Add(member); } } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Workspaces/Core/Portable/CodeActions/CodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CaseCorrection; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Tags; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// An action produced by a <see cref="CodeFixProvider"/> or a <see cref="CodeRefactoringProvider"/>. /// </summary> public abstract class CodeAction { /// <summary> /// A short title describing the action that may appear in a menu. /// </summary> public abstract string Title { get; } internal virtual string Message => Title; /// <summary> /// Two code actions are treated as equivalent if they have equal non-null <see cref="EquivalenceKey"/> values and were generated /// by the same <see cref="CodeFixProvider"/> or <see cref="CodeRefactoringProvider"/>. /// </summary> /// <remarks> /// Equivalence of code actions affects some Visual Studio behavior. For example, if multiple equivalent /// code actions result from code fixes or refactorings for a single Visual Studio light bulb instance, /// the light bulb UI will present only one code action from each set of equivalent code actions. /// Additionally, a Fix All operation will apply only code actions that are equivalent to the original code action. /// /// If two code actions that could be treated as equivalent do not have equal <see cref="EquivalenceKey"/> values, Visual Studio behavior /// may be less helpful than would be optimal. If two code actions that should be treated as distinct have /// equal <see cref="EquivalenceKey"/> values, Visual Studio behavior may appear incorrect. /// </remarks> public virtual string? EquivalenceKey => null; internal virtual bool IsInlinable => false; internal virtual CodeActionPriority Priority => CodeActionPriority.Medium; /// <summary> /// Descriptive tags from <see cref="WellKnownTags"/>. /// These tags may influence how the item is displayed. /// </summary> public virtual ImmutableArray<string> Tags => ImmutableArray<string>.Empty; internal virtual ImmutableArray<CodeAction> NestedCodeActions => ImmutableArray<CodeAction>.Empty; /// <summary> /// Gets custom tags for the CodeAction. /// </summary> internal ImmutableArray<string> CustomTags { get; set; } = ImmutableArray<string>.Empty; /// <summary> /// Used by the CodeFixService and CodeRefactoringService to add the Provider Name as a CustomTag. /// </summary> internal void AddCustomTag(string tag) { CustomTags = CustomTags.Add(tag); } /// <summary> /// The sequence of operations that define the code action. /// </summary> public Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync(CancellationToken cancellationToken) => GetOperationsAsync(new ProgressTracker(), cancellationToken); internal Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync( IProgressTracker progressTracker, CancellationToken cancellationToken) { return GetOperationsCoreAsync(progressTracker, cancellationToken); } /// <summary> /// The sequence of operations that define the code action. /// </summary> internal virtual async Task<ImmutableArray<CodeActionOperation>> GetOperationsCoreAsync( IProgressTracker progressTracker, CancellationToken cancellationToken) { var operations = await this.ComputeOperationsAsync(progressTracker, cancellationToken).ConfigureAwait(false); if (operations != null) { return await this.PostProcessAsync(operations, cancellationToken).ConfigureAwait(false); } return ImmutableArray<CodeActionOperation>.Empty; } /// <summary> /// The sequence of operations used to construct a preview. /// </summary> public async Task<ImmutableArray<CodeActionOperation>> GetPreviewOperationsAsync(CancellationToken cancellationToken) { var operations = await this.ComputePreviewOperationsAsync(cancellationToken).ConfigureAwait(false); if (operations != null) { return await this.PostProcessAsync(operations, cancellationToken).ConfigureAwait(false); } return ImmutableArray<CodeActionOperation>.Empty; } /// <summary> /// Override this method if you want to implement a <see cref="CodeAction"/> subclass that includes custom <see cref="CodeActionOperation"/>'s. /// </summary> protected virtual async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) { var changedSolution = await GetChangedSolutionAsync(cancellationToken).ConfigureAwait(false); if (changedSolution == null) { return Array.Empty<CodeActionOperation>(); } return new CodeActionOperation[] { new ApplyChangesOperation(changedSolution) }; } internal virtual async Task<ImmutableArray<CodeActionOperation>> ComputeOperationsAsync( IProgressTracker progressTracker, CancellationToken cancellationToken) { var operations = await ComputeOperationsAsync(cancellationToken).ConfigureAwait(false); return operations.ToImmutableArrayOrEmpty(); } /// <summary> /// Override this method if you want to implement a <see cref="CodeAction"/> that has a set of preview operations that are different /// than the operations produced by <see cref="ComputeOperationsAsync(CancellationToken)"/>. /// </summary> protected virtual Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken) => ComputeOperationsAsync(cancellationToken); /// <summary> /// Computes all changes for an entire solution. /// Override this method if you want to implement a <see cref="CodeAction"/> subclass that changes more than one document. /// </summary> protected virtual async Task<Solution?> GetChangedSolutionAsync(CancellationToken cancellationToken) { var changedDocument = await GetChangedDocumentAsync(cancellationToken).ConfigureAwait(false); if (changedDocument == null) { return null; } return changedDocument.Project.Solution; } internal virtual Task<Solution?> GetChangedSolutionAsync( IProgressTracker progressTracker, CancellationToken cancellationToken) { return GetChangedSolutionAsync(cancellationToken); } /// <summary> /// Computes changes for a single document. Override this method if you want to implement a /// <see cref="CodeAction"/> subclass that changes a single document. /// </summary> /// <remarks> /// All code actions are expected to operate on solutions. This method is a helper to simplify the /// implementation of <see cref="GetChangedSolutionAsync(CancellationToken)"/> for code actions that only need /// to change one document. /// </remarks> /// <exception cref="NotSupportedException">If this code action does not support changing a single document.</exception> protected virtual Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) => throw new NotSupportedException(GetType().FullName); /// <summary> /// used by batch fixer engine to get new solution /// </summary> internal async Task<Solution?> GetChangedSolutionInternalAsync(bool postProcessChanges = true, CancellationToken cancellationToken = default) { var solution = await GetChangedSolutionAsync(new ProgressTracker(), cancellationToken).ConfigureAwait(false); if (solution == null || !postProcessChanges) { return solution; } return await this.PostProcessChangesAsync(solution, cancellationToken).ConfigureAwait(false); } internal Task<Document> GetChangedDocumentInternalAsync(CancellationToken cancellation) => GetChangedDocumentAsync(cancellation); /// <summary> /// Apply post processing steps to any <see cref="ApplyChangesOperation"/>'s. /// </summary> /// <param name="operations">A list of operations.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns>A new list of operations with post processing steps applied to any <see cref="ApplyChangesOperation"/>'s.</returns> protected async Task<ImmutableArray<CodeActionOperation>> PostProcessAsync(IEnumerable<CodeActionOperation> operations, CancellationToken cancellationToken) { var arrayBuilder = new ArrayBuilder<CodeActionOperation>(); foreach (var op in operations) { if (op is ApplyChangesOperation ac) { arrayBuilder.Add(new ApplyChangesOperation(await this.PostProcessChangesAsync(ac.ChangedSolution, cancellationToken).ConfigureAwait(false))); } else { arrayBuilder.Add(op); } } return arrayBuilder.ToImmutableAndFree(); } /// <summary> /// Apply post processing steps to solution changes, like formatting and simplification. /// </summary> /// <param name="changedSolution">The solution changed by the <see cref="CodeAction"/>.</param> /// <param name="cancellationToken">A cancellation token</param> protected async Task<Solution> PostProcessChangesAsync(Solution changedSolution, CancellationToken cancellationToken) { var solutionChanges = changedSolution.GetChanges(changedSolution.Workspace.CurrentSolution); var processedSolution = changedSolution; // process changed projects foreach (var projectChanges in solutionChanges.GetProjectChanges()) { var documentsToProcess = projectChanges.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true).Concat( projectChanges.GetAddedDocuments()); foreach (var documentId in documentsToProcess) { var document = processedSolution.GetRequiredDocument(documentId); var processedDocument = await PostProcessChangesAsync(document, cancellationToken).ConfigureAwait(false); processedSolution = processedDocument.Project.Solution; } } // process completely new projects too foreach (var addedProject in solutionChanges.GetAddedProjects()) { var documentsToProcess = addedProject.DocumentIds; foreach (var documentId in documentsToProcess) { var document = processedSolution.GetRequiredDocument(documentId); var processedDocument = await PostProcessChangesAsync(document, cancellationToken).ConfigureAwait(false); processedSolution = processedDocument.Project.Solution; } } return processedSolution; } /// <summary> /// Apply post processing steps to a single document: /// Reducing nodes annotated with <see cref="Simplifier.Annotation"/> /// Formatting nodes annotated with <see cref="Formatter.Annotation"/> /// </summary> /// <param name="document">The document changed by the <see cref="CodeAction"/>.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns>A document with the post processing changes applied.</returns> protected virtual Task<Document> PostProcessChangesAsync(Document document, CancellationToken cancellationToken) => CleanupDocumentAsync(document, cancellationToken); internal static async Task<Document> CleanupDocumentAsync( Document document, CancellationToken cancellationToken) { if (document.SupportsSyntaxTree) { document = await ImportAdder.AddImportsFromSymbolAnnotationAsync( document, Simplifier.AddImportsAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false); document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); // format any node with explicit formatter annotation document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); // format any elastic whitespace document = await Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false); document = await CaseCorrector.CaseCorrectAsync(document, CaseCorrector.Annotation, cancellationToken).ConfigureAwait(false); } return document; } #region Factories for standard code actions /// <summary> /// Creates a <see cref="CodeAction"/> for a change to a single <see cref="Document"/>. /// Use this factory when the change is expensive to compute and should be deferred until requested. /// </summary> /// <param name="title">Title of the <see cref="CodeAction"/>.</param> /// <param name="createChangedDocument">Function to create the <see cref="Document"/>.</param> /// <param name="equivalenceKey">Optional value used to determine the equivalence of the <see cref="CodeAction"/> with other <see cref="CodeAction"/>s. See <see cref="CodeAction.EquivalenceKey"/>.</param> [SuppressMessage("ApiDesign", "RS0027:Public API with optional parameter(s) should have the most parameters amongst its public overloads.", Justification = "Preserving existing public API")] public static CodeAction Create(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string? equivalenceKey = null) { if (title == null) { throw new ArgumentNullException(nameof(title)); } if (createChangedDocument == null) { throw new ArgumentNullException(nameof(createChangedDocument)); } return new DocumentChangeAction(title, createChangedDocument, equivalenceKey); } /// <summary> /// Creates a <see cref="CodeAction"/> for a change to more than one <see cref="Document"/> within a <see cref="Solution"/>. /// Use this factory when the change is expensive to compute and should be deferred until requested. /// </summary> /// <param name="title">Title of the <see cref="CodeAction"/>.</param> /// <param name="createChangedSolution">Function to create the <see cref="Solution"/>.</param> /// <param name="equivalenceKey">Optional value used to determine the equivalence of the <see cref="CodeAction"/> with other <see cref="CodeAction"/>s. See <see cref="CodeAction.EquivalenceKey"/>.</param> [SuppressMessage("ApiDesign", "RS0027:Public API with optional parameter(s) should have the most parameters amongst its public overloads.", Justification = "Preserving existing public API")] public static CodeAction Create(string title, Func<CancellationToken, Task<Solution>> createChangedSolution, string? equivalenceKey = null) { if (title == null) { throw new ArgumentNullException(nameof(title)); } if (createChangedSolution == null) { throw new ArgumentNullException(nameof(createChangedSolution)); } return new SolutionChangeAction(title, createChangedSolution, equivalenceKey); } /// <summary> /// Creates a <see cref="CodeAction"/> representing a group of code actions. /// </summary> /// <param name="title">Title of the <see cref="CodeAction"/> group.</param> /// <param name="nestedActions">The code actions within the group.</param> /// <param name="isInlinable"><see langword="true"/> to allow inlining the members of the group into the parent; /// otherwise, <see langword="false"/> to require that this group appear as a group with nested actions.</param> public static CodeAction Create(string title, ImmutableArray<CodeAction> nestedActions, bool isInlinable) { if (title is null) { throw new ArgumentNullException(nameof(title)); } if (nestedActions == null) { throw new ArgumentNullException(nameof(nestedActions)); } return new CodeActionWithNestedActions(title, nestedActions, isInlinable); } internal abstract class SimpleCodeAction : CodeAction { public SimpleCodeAction( string title, string? equivalenceKey) { Title = title; EquivalenceKey = equivalenceKey; } public sealed override string Title { get; } public sealed override string? EquivalenceKey { get; } } internal class CodeActionWithNestedActions : SimpleCodeAction { public CodeActionWithNestedActions( string title, ImmutableArray<CodeAction> nestedActions, bool isInlinable, CodeActionPriority priority = CodeActionPriority.Medium) : base(title, ComputeEquivalenceKey(nestedActions)) { Debug.Assert(nestedActions.Length > 0); NestedCodeActions = nestedActions; IsInlinable = isInlinable; Priority = priority; } internal override CodeActionPriority Priority { get; } internal sealed override bool IsInlinable { get; } internal sealed override ImmutableArray<CodeAction> NestedCodeActions { get; } private static string? ComputeEquivalenceKey(ImmutableArray<CodeAction> nestedActions) { var equivalenceKey = StringBuilderPool.Allocate(); try { foreach (var action in nestedActions) { equivalenceKey.Append((action.EquivalenceKey ?? action.GetHashCode().ToString()) + ";"); } return equivalenceKey.Length > 0 ? equivalenceKey.ToString() : null; } finally { StringBuilderPool.ReturnAndFree(equivalenceKey); } } } internal class DocumentChangeAction : SimpleCodeAction { private readonly Func<CancellationToken, Task<Document>> _createChangedDocument; public DocumentChangeAction( string title, Func<CancellationToken, Task<Document>> createChangedDocument, string? equivalenceKey) : base(title, equivalenceKey) { _createChangedDocument = createChangedDocument; } protected sealed override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) => _createChangedDocument(cancellationToken); } internal class SolutionChangeAction : SimpleCodeAction { private readonly Func<CancellationToken, Task<Solution>> _createChangedSolution; public SolutionChangeAction( string title, Func<CancellationToken, Task<Solution>> createChangedSolution, string? equivalenceKey) : base(title, equivalenceKey) { _createChangedSolution = createChangedSolution; } protected sealed override Task<Solution?> GetChangedSolutionAsync(CancellationToken cancellationToken) => _createChangedSolution(cancellationToken).AsNullable(); } internal class NoChangeAction : SimpleCodeAction { public NoChangeAction( string title, string? equivalenceKey) : base(title, equivalenceKey) { } protected sealed override Task<Solution?> GetChangedSolutionAsync(CancellationToken cancellationToken) => SpecializedTasks.Null<Solution>(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CaseCorrection; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Tags; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// An action produced by a <see cref="CodeFixProvider"/> or a <see cref="CodeRefactoringProvider"/>. /// </summary> public abstract class CodeAction { /// <summary> /// A short title describing the action that may appear in a menu. /// </summary> public abstract string Title { get; } internal virtual string Message => Title; /// <summary> /// Two code actions are treated as equivalent if they have equal non-null <see cref="EquivalenceKey"/> values and were generated /// by the same <see cref="CodeFixProvider"/> or <see cref="CodeRefactoringProvider"/>. /// </summary> /// <remarks> /// Equivalence of code actions affects some Visual Studio behavior. For example, if multiple equivalent /// code actions result from code fixes or refactorings for a single Visual Studio light bulb instance, /// the light bulb UI will present only one code action from each set of equivalent code actions. /// Additionally, a Fix All operation will apply only code actions that are equivalent to the original code action. /// /// If two code actions that could be treated as equivalent do not have equal <see cref="EquivalenceKey"/> values, Visual Studio behavior /// may be less helpful than would be optimal. If two code actions that should be treated as distinct have /// equal <see cref="EquivalenceKey"/> values, Visual Studio behavior may appear incorrect. /// </remarks> public virtual string? EquivalenceKey => null; internal virtual bool IsInlinable => false; internal virtual CodeActionPriority Priority => CodeActionPriority.Medium; /// <summary> /// Descriptive tags from <see cref="WellKnownTags"/>. /// These tags may influence how the item is displayed. /// </summary> public virtual ImmutableArray<string> Tags => ImmutableArray<string>.Empty; internal virtual ImmutableArray<CodeAction> NestedCodeActions => ImmutableArray<CodeAction>.Empty; /// <summary> /// Gets custom tags for the CodeAction. /// </summary> internal ImmutableArray<string> CustomTags { get; set; } = ImmutableArray<string>.Empty; /// <summary> /// Used by the CodeFixService and CodeRefactoringService to add the Provider Name as a CustomTag. /// </summary> internal void AddCustomTag(string tag) { CustomTags = CustomTags.Add(tag); } /// <summary> /// The sequence of operations that define the code action. /// </summary> public Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync(CancellationToken cancellationToken) => GetOperationsAsync(new ProgressTracker(), cancellationToken); internal Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync( IProgressTracker progressTracker, CancellationToken cancellationToken) { return GetOperationsCoreAsync(progressTracker, cancellationToken); } /// <summary> /// The sequence of operations that define the code action. /// </summary> internal virtual async Task<ImmutableArray<CodeActionOperation>> GetOperationsCoreAsync( IProgressTracker progressTracker, CancellationToken cancellationToken) { var operations = await this.ComputeOperationsAsync(progressTracker, cancellationToken).ConfigureAwait(false); if (operations != null) { return await this.PostProcessAsync(operations, cancellationToken).ConfigureAwait(false); } return ImmutableArray<CodeActionOperation>.Empty; } /// <summary> /// The sequence of operations used to construct a preview. /// </summary> public async Task<ImmutableArray<CodeActionOperation>> GetPreviewOperationsAsync(CancellationToken cancellationToken) { var operations = await this.ComputePreviewOperationsAsync(cancellationToken).ConfigureAwait(false); if (operations != null) { return await this.PostProcessAsync(operations, cancellationToken).ConfigureAwait(false); } return ImmutableArray<CodeActionOperation>.Empty; } /// <summary> /// Override this method if you want to implement a <see cref="CodeAction"/> subclass that includes custom <see cref="CodeActionOperation"/>'s. /// </summary> protected virtual async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) { var changedSolution = await GetChangedSolutionAsync(cancellationToken).ConfigureAwait(false); if (changedSolution == null) { return Array.Empty<CodeActionOperation>(); } return new CodeActionOperation[] { new ApplyChangesOperation(changedSolution) }; } internal virtual async Task<ImmutableArray<CodeActionOperation>> ComputeOperationsAsync( IProgressTracker progressTracker, CancellationToken cancellationToken) { var operations = await ComputeOperationsAsync(cancellationToken).ConfigureAwait(false); return operations.ToImmutableArrayOrEmpty(); } /// <summary> /// Override this method if you want to implement a <see cref="CodeAction"/> that has a set of preview operations that are different /// than the operations produced by <see cref="ComputeOperationsAsync(CancellationToken)"/>. /// </summary> protected virtual Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken) => ComputeOperationsAsync(cancellationToken); /// <summary> /// Computes all changes for an entire solution. /// Override this method if you want to implement a <see cref="CodeAction"/> subclass that changes more than one document. /// </summary> protected virtual async Task<Solution?> GetChangedSolutionAsync(CancellationToken cancellationToken) { var changedDocument = await GetChangedDocumentAsync(cancellationToken).ConfigureAwait(false); if (changedDocument == null) { return null; } return changedDocument.Project.Solution; } internal virtual Task<Solution?> GetChangedSolutionAsync( IProgressTracker progressTracker, CancellationToken cancellationToken) { return GetChangedSolutionAsync(cancellationToken); } /// <summary> /// Computes changes for a single document. Override this method if you want to implement a /// <see cref="CodeAction"/> subclass that changes a single document. /// </summary> /// <remarks> /// All code actions are expected to operate on solutions. This method is a helper to simplify the /// implementation of <see cref="GetChangedSolutionAsync(CancellationToken)"/> for code actions that only need /// to change one document. /// </remarks> /// <exception cref="NotSupportedException">If this code action does not support changing a single document.</exception> protected virtual Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) => throw new NotSupportedException(GetType().FullName); /// <summary> /// used by batch fixer engine to get new solution /// </summary> internal async Task<Solution?> GetChangedSolutionInternalAsync(bool postProcessChanges = true, CancellationToken cancellationToken = default) { var solution = await GetChangedSolutionAsync(new ProgressTracker(), cancellationToken).ConfigureAwait(false); if (solution == null || !postProcessChanges) { return solution; } return await this.PostProcessChangesAsync(solution, cancellationToken).ConfigureAwait(false); } internal Task<Document> GetChangedDocumentInternalAsync(CancellationToken cancellation) => GetChangedDocumentAsync(cancellation); /// <summary> /// Apply post processing steps to any <see cref="ApplyChangesOperation"/>'s. /// </summary> /// <param name="operations">A list of operations.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns>A new list of operations with post processing steps applied to any <see cref="ApplyChangesOperation"/>'s.</returns> protected async Task<ImmutableArray<CodeActionOperation>> PostProcessAsync(IEnumerable<CodeActionOperation> operations, CancellationToken cancellationToken) { var arrayBuilder = new ArrayBuilder<CodeActionOperation>(); foreach (var op in operations) { if (op is ApplyChangesOperation ac) { arrayBuilder.Add(new ApplyChangesOperation(await this.PostProcessChangesAsync(ac.ChangedSolution, cancellationToken).ConfigureAwait(false))); } else { arrayBuilder.Add(op); } } return arrayBuilder.ToImmutableAndFree(); } /// <summary> /// Apply post processing steps to solution changes, like formatting and simplification. /// </summary> /// <param name="changedSolution">The solution changed by the <see cref="CodeAction"/>.</param> /// <param name="cancellationToken">A cancellation token</param> protected async Task<Solution> PostProcessChangesAsync(Solution changedSolution, CancellationToken cancellationToken) { var solutionChanges = changedSolution.GetChanges(changedSolution.Workspace.CurrentSolution); var processedSolution = changedSolution; // process changed projects foreach (var projectChanges in solutionChanges.GetProjectChanges()) { var documentsToProcess = projectChanges.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true).Concat( projectChanges.GetAddedDocuments()); foreach (var documentId in documentsToProcess) { var document = processedSolution.GetRequiredDocument(documentId); var processedDocument = await PostProcessChangesAsync(document, cancellationToken).ConfigureAwait(false); processedSolution = processedDocument.Project.Solution; } } // process completely new projects too foreach (var addedProject in solutionChanges.GetAddedProjects()) { var documentsToProcess = addedProject.DocumentIds; foreach (var documentId in documentsToProcess) { var document = processedSolution.GetRequiredDocument(documentId); var processedDocument = await PostProcessChangesAsync(document, cancellationToken).ConfigureAwait(false); processedSolution = processedDocument.Project.Solution; } } return processedSolution; } /// <summary> /// Apply post processing steps to a single document: /// Reducing nodes annotated with <see cref="Simplifier.Annotation"/> /// Formatting nodes annotated with <see cref="Formatter.Annotation"/> /// </summary> /// <param name="document">The document changed by the <see cref="CodeAction"/>.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns>A document with the post processing changes applied.</returns> protected virtual Task<Document> PostProcessChangesAsync(Document document, CancellationToken cancellationToken) => CleanupDocumentAsync(document, cancellationToken); internal static async Task<Document> CleanupDocumentAsync( Document document, CancellationToken cancellationToken) { if (document.SupportsSyntaxTree) { document = await ImportAdder.AddImportsFromSymbolAnnotationAsync( document, Simplifier.AddImportsAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false); document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); // format any node with explicit formatter annotation document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); // format any elastic whitespace document = await Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false); document = await CaseCorrector.CaseCorrectAsync(document, CaseCorrector.Annotation, cancellationToken).ConfigureAwait(false); } return document; } #region Factories for standard code actions /// <summary> /// Creates a <see cref="CodeAction"/> for a change to a single <see cref="Document"/>. /// Use this factory when the change is expensive to compute and should be deferred until requested. /// </summary> /// <param name="title">Title of the <see cref="CodeAction"/>.</param> /// <param name="createChangedDocument">Function to create the <see cref="Document"/>.</param> /// <param name="equivalenceKey">Optional value used to determine the equivalence of the <see cref="CodeAction"/> with other <see cref="CodeAction"/>s. See <see cref="CodeAction.EquivalenceKey"/>.</param> [SuppressMessage("ApiDesign", "RS0027:Public API with optional parameter(s) should have the most parameters amongst its public overloads.", Justification = "Preserving existing public API")] public static CodeAction Create(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string? equivalenceKey = null) { if (title == null) { throw new ArgumentNullException(nameof(title)); } if (createChangedDocument == null) { throw new ArgumentNullException(nameof(createChangedDocument)); } return new DocumentChangeAction(title, createChangedDocument, equivalenceKey); } /// <summary> /// Creates a <see cref="CodeAction"/> for a change to more than one <see cref="Document"/> within a <see cref="Solution"/>. /// Use this factory when the change is expensive to compute and should be deferred until requested. /// </summary> /// <param name="title">Title of the <see cref="CodeAction"/>.</param> /// <param name="createChangedSolution">Function to create the <see cref="Solution"/>.</param> /// <param name="equivalenceKey">Optional value used to determine the equivalence of the <see cref="CodeAction"/> with other <see cref="CodeAction"/>s. See <see cref="CodeAction.EquivalenceKey"/>.</param> [SuppressMessage("ApiDesign", "RS0027:Public API with optional parameter(s) should have the most parameters amongst its public overloads.", Justification = "Preserving existing public API")] public static CodeAction Create(string title, Func<CancellationToken, Task<Solution>> createChangedSolution, string? equivalenceKey = null) { if (title == null) { throw new ArgumentNullException(nameof(title)); } if (createChangedSolution == null) { throw new ArgumentNullException(nameof(createChangedSolution)); } return new SolutionChangeAction(title, createChangedSolution, equivalenceKey); } /// <summary> /// Creates a <see cref="CodeAction"/> representing a group of code actions. /// </summary> /// <param name="title">Title of the <see cref="CodeAction"/> group.</param> /// <param name="nestedActions">The code actions within the group.</param> /// <param name="isInlinable"><see langword="true"/> to allow inlining the members of the group into the parent; /// otherwise, <see langword="false"/> to require that this group appear as a group with nested actions.</param> public static CodeAction Create(string title, ImmutableArray<CodeAction> nestedActions, bool isInlinable) { if (title is null) { throw new ArgumentNullException(nameof(title)); } if (nestedActions == null) { throw new ArgumentNullException(nameof(nestedActions)); } return new CodeActionWithNestedActions(title, nestedActions, isInlinable); } internal abstract class SimpleCodeAction : CodeAction { public SimpleCodeAction( string title, string? equivalenceKey) { Title = title; EquivalenceKey = equivalenceKey; } public sealed override string Title { get; } public sealed override string? EquivalenceKey { get; } } internal class CodeActionWithNestedActions : SimpleCodeAction { public CodeActionWithNestedActions( string title, ImmutableArray<CodeAction> nestedActions, bool isInlinable, CodeActionPriority priority = CodeActionPriority.Medium) : base(title, ComputeEquivalenceKey(nestedActions)) { Debug.Assert(nestedActions.Length > 0); NestedCodeActions = nestedActions; IsInlinable = isInlinable; Priority = priority; } internal override CodeActionPriority Priority { get; } internal sealed override bool IsInlinable { get; } internal sealed override ImmutableArray<CodeAction> NestedCodeActions { get; } private static string? ComputeEquivalenceKey(ImmutableArray<CodeAction> nestedActions) { var equivalenceKey = StringBuilderPool.Allocate(); try { foreach (var action in nestedActions) { equivalenceKey.Append((action.EquivalenceKey ?? action.GetHashCode().ToString()) + ";"); } return equivalenceKey.Length > 0 ? equivalenceKey.ToString() : null; } finally { StringBuilderPool.ReturnAndFree(equivalenceKey); } } } internal class DocumentChangeAction : SimpleCodeAction { private readonly Func<CancellationToken, Task<Document>> _createChangedDocument; public DocumentChangeAction( string title, Func<CancellationToken, Task<Document>> createChangedDocument, string? equivalenceKey) : base(title, equivalenceKey) { _createChangedDocument = createChangedDocument; } protected sealed override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) => _createChangedDocument(cancellationToken); } internal class SolutionChangeAction : SimpleCodeAction { private readonly Func<CancellationToken, Task<Solution>> _createChangedSolution; public SolutionChangeAction( string title, Func<CancellationToken, Task<Solution>> createChangedSolution, string? equivalenceKey) : base(title, equivalenceKey) { _createChangedSolution = createChangedSolution; } protected sealed override Task<Solution?> GetChangedSolutionAsync(CancellationToken cancellationToken) => _createChangedSolution(cancellationToken).AsNullable(); } internal class NoChangeAction : SimpleCodeAction { public NoChangeAction( string title, string? equivalenceKey) : base(title, equivalenceKey) { } protected sealed override Task<Solution?> GetChangedSolutionAsync(CancellationToken cancellationToken) => SpecializedTasks.Null<Solution>(); } #endregion } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Workspaces/Core/Portable/Workspace/Solution/AdditionalTextWithState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// An implementation of <see cref="AdditionalText"/> for the compiler that wraps a <see cref="AdditionalDocumentState"/>. /// </summary> internal sealed class AdditionalTextWithState : AdditionalText { private readonly AdditionalDocumentState _documentState; /// <summary> /// Create a <see cref="SourceText"/> from a <see cref="AdditionalDocumentState"/>. /// </summary> public AdditionalTextWithState(AdditionalDocumentState documentState) => _documentState = documentState ?? throw new ArgumentNullException(nameof(documentState)); /// <summary> /// Resolved path of the document. /// </summary> public override string Path => _documentState.FilePath ?? _documentState.Name; /// <summary> /// Retrieves a <see cref="SourceText"/> with the contents of this file. /// </summary> public override SourceText GetText(CancellationToken cancellationToken = default) { var text = _documentState.GetTextSynchronously(cancellationToken); return text; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// An implementation of <see cref="AdditionalText"/> for the compiler that wraps a <see cref="AdditionalDocumentState"/>. /// </summary> internal sealed class AdditionalTextWithState : AdditionalText { private readonly AdditionalDocumentState _documentState; /// <summary> /// Create a <see cref="SourceText"/> from a <see cref="AdditionalDocumentState"/>. /// </summary> public AdditionalTextWithState(AdditionalDocumentState documentState) => _documentState = documentState ?? throw new ArgumentNullException(nameof(documentState)); /// <summary> /// Resolved path of the document. /// </summary> public override string Path => _documentState.FilePath ?? _documentState.Name; /// <summary> /// Retrieves a <see cref="SourceText"/> with the contents of this file. /// </summary> public override SourceText GetText(CancellationToken cancellationToken = default) { var text = _documentState.GetTextSynchronously(cancellationToken); return text; } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Features/VisualBasic/Portable/Structure/Providers/UsingBlockStructureProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class UsingBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of UsingBlockSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As UsingBlockSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.UsingStatement, autoCollapse:=False, type:=BlockTypes.Statement, isCollapsible:=True)) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class UsingBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of UsingBlockSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As UsingBlockSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.UsingStatement, autoCollapse:=False, type:=BlockTypes.Statement, isCollapsible:=True)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation { public class SmartTokenFormatterFormatTokenTests : CSharpFormatterTestsBase { public SmartTokenFormatterFormatTokenTests(ITestOutputHelper output) : base(output) { } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task EmptyFile1() { var code = @"{"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 0, expectedSpace: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmptyFile2() { var code = @"}"; await ExpectException_SmartTokenFormatterCloseBraceAsync( code, indentationLine: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace1() { var code = @"namespace NS {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 1, expectedSpace: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace2() { var code = @"namespace NS }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 1, expectedSpace: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace3() { var code = @"namespace NS { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 2, expectedSpace: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class1() { var code = @"namespace NS { class Class {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 3, expectedSpace: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class2() { var code = @"namespace NS { class Class }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 3, expectedSpace: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class3() { var code = @"namespace NS { class Class { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 4, expectedSpace: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Method1() { var code = @"namespace NS { class Class { void Method(int i) {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 5, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Method2() { var code = @"namespace NS { class Class { void Method(int i) }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 5, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Method3() { var code = @"namespace NS { class Class { void Method(int i) { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 6, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Property1() { var code = @"namespace NS { class Class { int Goo {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 5, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Property2() { var code = @"namespace NS { class Class { int Goo { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 6, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Event1() { var code = @"namespace NS { class Class { event EventHandler Goo {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 5, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Event2() { var code = @"namespace NS { class Class { event EventHandler Goo { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 6, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Indexer1() { var code = @"namespace NS { class Class { int this[int index] {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 5, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Indexer2() { var code = @"namespace NS { class Class { int this[int index] { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 6, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block1() { var code = @"namespace NS { class Class { void Method(int i) { {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 6, expectedSpace: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block2() { var code = @"namespace NS { class Class { void Method(int i) } }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 6, expectedSpace: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block3() { var code = @"namespace NS { class Class { void Method(int i) { { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 7, expectedSpace: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block4() { var code = @"namespace NS { class Class { void Method(int i) { { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 7, expectedSpace: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer1() { var code = @"namespace NS { class Class { void Method(int i) { var a = new [] { }"; var expected = @"namespace NS { class Class { void Method(int i) { var a = new [] { }"; await AssertSmartTokenFormatterOpenBraceAsync( expected, code, indentationLine: 6); } [Fact] [WorkItem(537827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537827")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer3() { var code = @"namespace NS { class Class { void Method(int i) { int[,] arr = { {1,1}, {2,2} } }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 9, expectedSpace: 12); } [Fact] [WorkItem(543142, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543142")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EnterWithTrailingWhitespace() { var code = @"class Class { void Method(int i) { var a = new { }; "; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 5, expectedSpace: 8); } [WorkItem(9216, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task OpenBraceWithBaseIndentation() { var markup = @" class C { void M() { [|#line ""Default.aspx"", 273 if (true) $${ } #line default #line hidden|] } }"; await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup, baseIndentation: 7, expectedIndentation: 11); } [WorkItem(9216, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task CloseBraceWithBaseIndentation() { var markup = @" class C { void M() { [|#line ""Default.aspx"", 273 if (true) { $$} #line default #line hidden|] } }"; await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup, baseIndentation: 7, expectedIndentation: 11); } [WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TestPreprocessor() { var code = @" class C { void M() { # } }"; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: '#', useTabs: false); Assert.Equal(0, actualIndentation); actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 5, ch: '#', useTabs: true); Assert.Equal(0, actualIndentation); } [WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TestRegion() { var code = @" class C { void M() { #region } }"; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n', useTabs: false); Assert.Equal(8, actualIndentation); actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 5, ch: 'n', useTabs: true); Assert.Equal(8, actualIndentation); } [WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TestEndRegion() { var code = @" class C { void M() { #region #endregion } }"; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n', useTabs: false); Assert.Equal(8, actualIndentation); actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 5, ch: 'n', useTabs: true); Assert.Equal(8, actualIndentation); } [WorkItem(777467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TestSelect() { var code = @" using System; using System.Linq; class Program { static IEnumerable<int> Goo() { return from a in new[] { 1, 2, 3 } select } } "; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 't', useTabs: false); Assert.Equal(15, actualIndentation); actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 9, ch: 't', useTabs: true); Assert.Equal(15, actualIndentation); } [WorkItem(777467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TestWhere() { var code = @" using System; using System.Linq; class Program { static IEnumerable<int> Goo() { return from a in new[] { 1, 2, 3 } where } } "; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 'e', useTabs: false); Assert.Equal(15, actualIndentation); actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 9, ch: 'e', useTabs: true); Assert.Equal(15, actualIndentation); } private static async Task AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(string markup, int baseIndentation, int expectedIndentation) { await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup, baseIndentation, expectedIndentation, useTabs: false).ConfigureAwait(false); await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup.Replace(" ", "\t"), baseIndentation, expectedIndentation, useTabs: true).ConfigureAwait(false); } private static Task AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(string markup, int baseIndentation, int expectedIndentation, bool useTabs) { MarkupTestFile.GetPositionAndSpan(markup, out var code, out var position, out TextSpan span); return AssertSmartTokenFormatterOpenBraceAsync( code, SourceText.From(code).Lines.IndexOf(position), expectedIndentation, useTabs, baseIndentation, span); } private static async Task AssertSmartTokenFormatterOpenBraceAsync( string code, int indentationLine, int expectedSpace, int? baseIndentation = null, TextSpan span = default) { await AssertSmartTokenFormatterOpenBraceAsync(code, indentationLine, expectedSpace, useTabs: false, baseIndentation, span).ConfigureAwait(false); await AssertSmartTokenFormatterOpenBraceAsync(code.Replace(" ", "\t"), indentationLine, expectedSpace, useTabs: true, baseIndentation, span).ConfigureAwait(false); } private static async Task AssertSmartTokenFormatterOpenBraceAsync( string code, int indentationLine, int expectedSpace, bool useTabs, int? baseIndentation, TextSpan span) { var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '{', useTabs, baseIndentation, span); Assert.Equal(expectedSpace, actualIndentation); } private static async Task AssertSmartTokenFormatterOpenBraceAsync( string expected, string code, int indentationLine) { await AssertSmartTokenFormatterOpenBraceAsync(expected, code, indentationLine, useTabs: false).ConfigureAwait(false); await AssertSmartTokenFormatterOpenBraceAsync(expected.Replace(" ", "\t"), code.Replace(" ", "\t"), indentationLine, useTabs: true).ConfigureAwait(false); } private static async Task AssertSmartTokenFormatterOpenBraceAsync( string expected, string code, int indentationLine, bool useTabs) { // create tree service using var workspace = TestWorkspace.CreateCSharp(code); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs))); var buffer = workspace.Documents.First().GetTextBuffer(); var actual = await TokenFormatAsync(workspace, buffer, indentationLine, '{'); Assert.Equal(expected, actual); } private static async Task AssertSmartTokenFormatterCloseBraceWithBaseIndentation(string markup, int baseIndentation, int expectedIndentation) { await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup, baseIndentation, expectedIndentation, useTabs: false).ConfigureAwait(false); await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup.Replace(" ", "\t"), baseIndentation, expectedIndentation, useTabs: true).ConfigureAwait(false); } private static Task AssertSmartTokenFormatterCloseBraceWithBaseIndentation(string markup, int baseIndentation, int expectedIndentation, bool useTabs) { MarkupTestFile.GetPositionAndSpan(markup, out var code, out var position, out TextSpan span); return AssertSmartTokenFormatterCloseBraceAsync( code, SourceText.From(code).Lines.IndexOf(position), expectedIndentation, useTabs, baseIndentation, span); } private static async Task AssertSmartTokenFormatterCloseBraceAsync( string code, int indentationLine, int expectedSpace, int? baseIndentation = null, TextSpan span = default) { await AssertSmartTokenFormatterCloseBraceAsync(code, indentationLine, expectedSpace, useTabs: false, baseIndentation, span).ConfigureAwait(false); await AssertSmartTokenFormatterCloseBraceAsync(code.Replace(" ", "\t"), indentationLine, expectedSpace, useTabs: true, baseIndentation, span).ConfigureAwait(false); } private static async Task AssertSmartTokenFormatterCloseBraceAsync( string code, int indentationLine, int expectedSpace, bool useTabs, int? baseIndentation, TextSpan span) { var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '}', useTabs, baseIndentation, span); Assert.Equal(expectedSpace, actualIndentation); } private static async Task ExpectException_SmartTokenFormatterCloseBraceAsync( string code, int indentationLine) { await ExpectException_SmartTokenFormatterCloseBraceAsync(code, indentationLine, useTabs: false).ConfigureAwait(false); await ExpectException_SmartTokenFormatterCloseBraceAsync(code.Replace(" ", "\t"), indentationLine, useTabs: true).ConfigureAwait(false); } private static async Task ExpectException_SmartTokenFormatterCloseBraceAsync( string code, int indentationLine, bool useTabs) { Assert.NotNull(await Record.ExceptionAsync(() => GetSmartTokenFormatterIndentationAsync(code, indentationLine, '}', useTabs))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation { public class SmartTokenFormatterFormatTokenTests : CSharpFormatterTestsBase { public SmartTokenFormatterFormatTokenTests(ITestOutputHelper output) : base(output) { } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task EmptyFile1() { var code = @"{"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 0, expectedSpace: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmptyFile2() { var code = @"}"; await ExpectException_SmartTokenFormatterCloseBraceAsync( code, indentationLine: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace1() { var code = @"namespace NS {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 1, expectedSpace: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace2() { var code = @"namespace NS }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 1, expectedSpace: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace3() { var code = @"namespace NS { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 2, expectedSpace: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class1() { var code = @"namespace NS { class Class {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 3, expectedSpace: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class2() { var code = @"namespace NS { class Class }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 3, expectedSpace: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class3() { var code = @"namespace NS { class Class { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 4, expectedSpace: 4); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Method1() { var code = @"namespace NS { class Class { void Method(int i) {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 5, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Method2() { var code = @"namespace NS { class Class { void Method(int i) }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 5, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Method3() { var code = @"namespace NS { class Class { void Method(int i) { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 6, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Property1() { var code = @"namespace NS { class Class { int Goo {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 5, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Property2() { var code = @"namespace NS { class Class { int Goo { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 6, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Event1() { var code = @"namespace NS { class Class { event EventHandler Goo {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 5, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Event2() { var code = @"namespace NS { class Class { event EventHandler Goo { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 6, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Indexer1() { var code = @"namespace NS { class Class { int this[int index] {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 5, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Indexer2() { var code = @"namespace NS { class Class { int this[int index] { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 6, expectedSpace: 8); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block1() { var code = @"namespace NS { class Class { void Method(int i) { {"; await AssertSmartTokenFormatterOpenBraceAsync( code, indentationLine: 6, expectedSpace: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block2() { var code = @"namespace NS { class Class { void Method(int i) } }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 6, expectedSpace: 0); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block3() { var code = @"namespace NS { class Class { void Method(int i) { { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 7, expectedSpace: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block4() { var code = @"namespace NS { class Class { void Method(int i) { { }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 7, expectedSpace: 12); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer1() { var code = @"namespace NS { class Class { void Method(int i) { var a = new [] { }"; var expected = @"namespace NS { class Class { void Method(int i) { var a = new [] { }"; await AssertSmartTokenFormatterOpenBraceAsync( expected, code, indentationLine: 6); } [Fact] [WorkItem(537827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537827")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer3() { var code = @"namespace NS { class Class { void Method(int i) { int[,] arr = { {1,1}, {2,2} } }"; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 9, expectedSpace: 12); } [Fact] [WorkItem(543142, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543142")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EnterWithTrailingWhitespace() { var code = @"class Class { void Method(int i) { var a = new { }; "; await AssertSmartTokenFormatterCloseBraceAsync( code, indentationLine: 5, expectedSpace: 8); } [WorkItem(9216, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task OpenBraceWithBaseIndentation() { var markup = @" class C { void M() { [|#line ""Default.aspx"", 273 if (true) $${ } #line default #line hidden|] } }"; await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup, baseIndentation: 7, expectedIndentation: 11); } [WorkItem(9216, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task CloseBraceWithBaseIndentation() { var markup = @" class C { void M() { [|#line ""Default.aspx"", 273 if (true) { $$} #line default #line hidden|] } }"; await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup, baseIndentation: 7, expectedIndentation: 11); } [WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TestPreprocessor() { var code = @" class C { void M() { # } }"; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: '#', useTabs: false); Assert.Equal(0, actualIndentation); actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 5, ch: '#', useTabs: true); Assert.Equal(0, actualIndentation); } [WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TestRegion() { var code = @" class C { void M() { #region } }"; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n', useTabs: false); Assert.Equal(8, actualIndentation); actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 5, ch: 'n', useTabs: true); Assert.Equal(8, actualIndentation); } [WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TestEndRegion() { var code = @" class C { void M() { #region #endregion } }"; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n', useTabs: false); Assert.Equal(8, actualIndentation); actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 5, ch: 'n', useTabs: true); Assert.Equal(8, actualIndentation); } [WorkItem(777467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TestSelect() { var code = @" using System; using System.Linq; class Program { static IEnumerable<int> Goo() { return from a in new[] { 1, 2, 3 } select } } "; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 't', useTabs: false); Assert.Equal(15, actualIndentation); actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 9, ch: 't', useTabs: true); Assert.Equal(15, actualIndentation); } [WorkItem(777467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")] [Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TestWhere() { var code = @" using System; using System.Linq; class Program { static IEnumerable<int> Goo() { return from a in new[] { 1, 2, 3 } where } } "; var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 'e', useTabs: false); Assert.Equal(15, actualIndentation); actualIndentation = await GetSmartTokenFormatterIndentationAsync(code.Replace(" ", "\t"), indentationLine: 9, ch: 'e', useTabs: true); Assert.Equal(15, actualIndentation); } private static async Task AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(string markup, int baseIndentation, int expectedIndentation) { await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup, baseIndentation, expectedIndentation, useTabs: false).ConfigureAwait(false); await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup.Replace(" ", "\t"), baseIndentation, expectedIndentation, useTabs: true).ConfigureAwait(false); } private static Task AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(string markup, int baseIndentation, int expectedIndentation, bool useTabs) { MarkupTestFile.GetPositionAndSpan(markup, out var code, out var position, out TextSpan span); return AssertSmartTokenFormatterOpenBraceAsync( code, SourceText.From(code).Lines.IndexOf(position), expectedIndentation, useTabs, baseIndentation, span); } private static async Task AssertSmartTokenFormatterOpenBraceAsync( string code, int indentationLine, int expectedSpace, int? baseIndentation = null, TextSpan span = default) { await AssertSmartTokenFormatterOpenBraceAsync(code, indentationLine, expectedSpace, useTabs: false, baseIndentation, span).ConfigureAwait(false); await AssertSmartTokenFormatterOpenBraceAsync(code.Replace(" ", "\t"), indentationLine, expectedSpace, useTabs: true, baseIndentation, span).ConfigureAwait(false); } private static async Task AssertSmartTokenFormatterOpenBraceAsync( string code, int indentationLine, int expectedSpace, bool useTabs, int? baseIndentation, TextSpan span) { var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '{', useTabs, baseIndentation, span); Assert.Equal(expectedSpace, actualIndentation); } private static async Task AssertSmartTokenFormatterOpenBraceAsync( string expected, string code, int indentationLine) { await AssertSmartTokenFormatterOpenBraceAsync(expected, code, indentationLine, useTabs: false).ConfigureAwait(false); await AssertSmartTokenFormatterOpenBraceAsync(expected.Replace(" ", "\t"), code.Replace(" ", "\t"), indentationLine, useTabs: true).ConfigureAwait(false); } private static async Task AssertSmartTokenFormatterOpenBraceAsync( string expected, string code, int indentationLine, bool useTabs) { // create tree service using var workspace = TestWorkspace.CreateCSharp(code); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs))); var buffer = workspace.Documents.First().GetTextBuffer(); var actual = await TokenFormatAsync(workspace, buffer, indentationLine, '{'); Assert.Equal(expected, actual); } private static async Task AssertSmartTokenFormatterCloseBraceWithBaseIndentation(string markup, int baseIndentation, int expectedIndentation) { await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup, baseIndentation, expectedIndentation, useTabs: false).ConfigureAwait(false); await AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup.Replace(" ", "\t"), baseIndentation, expectedIndentation, useTabs: true).ConfigureAwait(false); } private static Task AssertSmartTokenFormatterCloseBraceWithBaseIndentation(string markup, int baseIndentation, int expectedIndentation, bool useTabs) { MarkupTestFile.GetPositionAndSpan(markup, out var code, out var position, out TextSpan span); return AssertSmartTokenFormatterCloseBraceAsync( code, SourceText.From(code).Lines.IndexOf(position), expectedIndentation, useTabs, baseIndentation, span); } private static async Task AssertSmartTokenFormatterCloseBraceAsync( string code, int indentationLine, int expectedSpace, int? baseIndentation = null, TextSpan span = default) { await AssertSmartTokenFormatterCloseBraceAsync(code, indentationLine, expectedSpace, useTabs: false, baseIndentation, span).ConfigureAwait(false); await AssertSmartTokenFormatterCloseBraceAsync(code.Replace(" ", "\t"), indentationLine, expectedSpace, useTabs: true, baseIndentation, span).ConfigureAwait(false); } private static async Task AssertSmartTokenFormatterCloseBraceAsync( string code, int indentationLine, int expectedSpace, bool useTabs, int? baseIndentation, TextSpan span) { var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '}', useTabs, baseIndentation, span); Assert.Equal(expectedSpace, actualIndentation); } private static async Task ExpectException_SmartTokenFormatterCloseBraceAsync( string code, int indentationLine) { await ExpectException_SmartTokenFormatterCloseBraceAsync(code, indentationLine, useTabs: false).ConfigureAwait(false); await ExpectException_SmartTokenFormatterCloseBraceAsync(code.Replace(" ", "\t"), indentationLine, useTabs: true).ConfigureAwait(false); } private static async Task ExpectException_SmartTokenFormatterCloseBraceAsync( string code, int indentationLine, bool useTabs) { Assert.NotNull(await Record.ExceptionAsync(() => GetSmartTokenFormatterIndentationAsync(code, indentationLine, '}', useTabs))); } } }
-1
dotnet/roslyn
55,446
Bug fix extract local function errors C#7 and below
Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
akhera99
2021-08-05T21:48:32Z
2021-08-20T23:29:46Z
ab54a0fe8ce4439fa04c46bedf7de0a2db402363
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
Bug fix extract local function errors C#7 and below. Fixes: #55031 Opts to capture variables instead of creating new parameters in language versions below c#8 because they do not support static local functions. * Need to fix the call to the new method
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/xlf/VisualBasicWorkspaceExtensionsResources.tr.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="tr" original="../VisualBasicWorkspaceExtensionsResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Başka bir değer eklendiğinde bu değeri kaldırın.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="tr" original="../VisualBasicWorkspaceExtensionsResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Başka bir değer eklendiğinde bu değeri kaldırın.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion { /// <summary> /// csharp automatic line ender command handler /// </summary> [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(PredefinedCommandHandlerNames.AutomaticLineEnder)] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] internal partial class AutomaticLineEnderCommandHandler : AbstractAutomaticLineEnderCommandHandler { private static readonly string s_semicolon = SyntaxFacts.GetText(SyntaxKind.SemicolonToken); /// <summary> /// Annotation to locate the open brace token. /// </summary> private static readonly SyntaxAnnotation s_openBracePositionAnnotation = new(); /// <summary> /// Annotation to locate the replacement node(with or without braces). /// </summary> private static readonly SyntaxAnnotation s_replacementNodeAnnotation = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AutomaticLineEnderCommandHandler( ITextUndoHistoryRegistry undoRegistry, IEditorOperationsFactoryService editorOperations) : base(undoRegistry, editorOperations) { } protected override void NextAction(IEditorOperations editorOperation, Action nextAction) => editorOperation.InsertNewLine(); protected override bool TreatAsReturn(Document document, int caretPosition, CancellationToken cancellationToken) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var endToken = root.FindToken(caretPosition); if (endToken.IsMissing) { return false; } var tokenToLeft = root.FindTokenOnLeftOfPosition(caretPosition); var startToken = endToken.GetPreviousToken(); // case 1: // Consider code like so: try {|} // With auto brace completion on, user types `{` and `Return` in a hurry. // During typing, it is possible that shift was still down and not released after typing `{`. // So we've got an unintentional `shift + enter` and also we have nothing to complete this, // so we put in a newline, // which generates code like so : try { } // | // which is not useful as : try { // | // } // To support this, we treat `shift + enter` like `enter` here. var afterOpenBrace = startToken.Kind() == SyntaxKind.OpenBraceToken && endToken.Kind() == SyntaxKind.CloseBraceToken && tokenToLeft == startToken && endToken.Parent.IsKind(SyntaxKind.Block) && FormattingRangeHelper.AreTwoTokensOnSameLine(startToken, endToken); return afterOpenBrace; } protected override Document FormatAndApplyBasedOnEndToken(Document document, int position, CancellationToken cancellationToken) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var endToken = root.FindToken(position); var span = GetFormattedTextSpan(root, endToken); if (span == null) { return document; } var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var changes = Formatter.GetFormattedTextChanges( root, new[] { CommonFormattingHelpers.GetFormattingSpan(root, span.Value) }, document.Project.Solution.Workspace, options, rules: null, // use default cancellationToken: cancellationToken); return document.ApplyTextChanges(changes, cancellationToken); } private static TextSpan? GetFormattedTextSpan(SyntaxNode root, SyntaxToken endToken) { if (endToken.IsMissing) { return null; } var ranges = FormattingRangeHelper.FindAppropriateRange(endToken, useDefaultRange: false); if (ranges == null) { return null; } var startToken = ranges.Value.Item1; if (startToken.IsMissing || startToken.Kind() == SyntaxKind.None) { return null; } return CommonFormattingHelpers.GetFormattingSpan(root, TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End)); } #region SemicolonAppending protected override string? GetEndingString(Document document, int position, CancellationToken cancellationToken) { // prepare expansive information from document var tree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var root = tree.GetRoot(cancellationToken); var text = tree.GetText(cancellationToken); // Go through the set of owning nodes in leaf to root chain. foreach (var owningNode in GetOwningNodes(root, position)) { if (!TryGetLastToken(text, position, owningNode, out var lastToken)) { // If we can't get last token, there is nothing more to do, just skip // the other owning nodes and return. return null; } if (!CheckLocation(text, position, owningNode, lastToken)) { // If we failed this check, we indeed got the intended owner node and // inserting line ender here would introduce errors. return null; } // so far so good. we only add semi-colon if it makes statement syntax error free var textToParse = owningNode.NormalizeWhitespace().ToFullString() + s_semicolon; // currently, Parsing a field is not supported. as a workaround, wrap the field in a type and parse var node = ParseNode(tree, owningNode, textToParse); // Insert line ender if we didn't introduce any diagnostics, if not try the next owning node. if (node != null && !node.ContainsDiagnostics) { return s_semicolon; } } return null; } private static SyntaxNode? ParseNode(SyntaxTree tree, SyntaxNode owningNode, string textToParse) => owningNode switch { BaseFieldDeclarationSyntax => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options), BaseMethodDeclarationSyntax => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options), BasePropertyDeclarationSyntax => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options), StatementSyntax => SyntaxFactory.ParseStatement(textToParse, options: (CSharpParseOptions)tree.Options), UsingDirectiveSyntax => SyntaxFactory.ParseCompilationUnit(textToParse, options: (CSharpParseOptions)tree.Options), _ => null, }; /// <summary> /// wrap field in type /// </summary> private static string WrapInType(string textToParse) => "class C { " + textToParse + " }"; /// <summary> /// make sure current location is okay to put semicolon /// </summary> private static bool CheckLocation(SourceText text, int position, SyntaxNode owningNode, SyntaxToken lastToken) { var line = text.Lines.GetLineFromPosition(position); // if caret is at the end of the line and containing statement is expression statement // don't do anything if (position == line.End && owningNode is ExpressionStatementSyntax) { return false; } var locatedAtTheEndOfLine = LocatedAtTheEndOfLine(line, lastToken); // make sure that there is no trailing text after last token on the line if it is not at the end of the line if (!locatedAtTheEndOfLine) { var endingString = text.ToString(TextSpan.FromBounds(lastToken.Span.End, line.End)); if (!string.IsNullOrWhiteSpace(endingString)) { return false; } } // check whether using has contents if (owningNode is UsingDirectiveSyntax u && u.Name.IsMissing) { return false; } // make sure there is no open string literals var previousToken = lastToken.GetPreviousToken(); if (previousToken.Kind() == SyntaxKind.StringLiteralToken && previousToken.ToString().Last() != '"') { return false; } if (previousToken.Kind() == SyntaxKind.CharacterLiteralToken && previousToken.ToString().Last() != '\'') { return false; } // now, check embedded statement case if (owningNode.IsEmbeddedStatementOwner()) { var embeddedStatement = owningNode.GetEmbeddedStatement(); if (embeddedStatement == null || embeddedStatement.Span.IsEmpty) { return false; } } return true; } /// <summary> /// get last token of the given using/field/statement/expression bodied member if one exists /// </summary> private static bool TryGetLastToken(SourceText text, int position, SyntaxNode owningNode, out SyntaxToken lastToken) { lastToken = owningNode.GetLastToken(includeZeroWidth: true); // last token must be on the same line as the caret var line = text.Lines.GetLineFromPosition(position); var locatedAtTheEndOfLine = LocatedAtTheEndOfLine(line, lastToken); if (!locatedAtTheEndOfLine && text.Lines.IndexOf(lastToken.Span.End) != line.LineNumber) { return false; } // if we already have last semicolon, we don't need to do anything if (!lastToken.IsMissing && lastToken.Kind() == SyntaxKind.SemicolonToken) { return false; } return true; } /// <summary> /// check whether the line is located at the end of the line /// </summary> private static bool LocatedAtTheEndOfLine(TextLine line, SyntaxToken lastToken) => lastToken.IsMissing && lastToken.Span.End == line.EndIncludingLineBreak; /// <summary> /// find owning usings/field/statement/expression-bodied member of the given position /// </summary> private static IEnumerable<SyntaxNode> GetOwningNodes(SyntaxNode root, int position) { // make sure caret position is somewhere we can find a token var token = root.FindTokenFromEnd(position); if (token.Kind() == SyntaxKind.None) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } return token.GetAncestors<SyntaxNode>() .Where(AllowedConstructs) .Select(OwningNode) .WhereNotNull(); } private static bool AllowedConstructs(SyntaxNode n) => n is StatementSyntax or BaseFieldDeclarationSyntax or UsingDirectiveSyntax or ArrowExpressionClauseSyntax; private static SyntaxNode? OwningNode(SyntaxNode n) => n is ArrowExpressionClauseSyntax ? n.Parent : n; #endregion #region BraceModification protected override void ModifySelectedNode( AutomaticLineEnderCommandArgs args, Document document, SyntaxNode selectedNode, bool addBrace, int caretPosition, CancellationToken cancellationToken) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); // Add braces for the selected node if (addBrace) { // For these syntax node, braces pair could be easily added by modify the syntax tree if (selectedNode is BaseTypeDeclarationSyntax or BaseMethodDeclarationSyntax or LocalFunctionStatementSyntax or FieldDeclarationSyntax or EventFieldDeclarationSyntax or AccessorDeclarationSyntax or ObjectCreationExpressionSyntax or WhileStatementSyntax or ForEachStatementSyntax or ForStatementSyntax or LockStatementSyntax or UsingStatementSyntax or DoStatementSyntax or IfStatementSyntax or ElseClauseSyntax) { // Add the braces and get the next caretPosition var (newRoot, nextCaretPosition) = AddBraceToSelectedNode(document, root, selectedNode, args.TextView.Options, cancellationToken); if (document.Project.Solution.Workspace.TryApplyChanges(document.WithSyntaxRoot(newRoot).Project.Solution)) { args.TextView.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(args.SubjectBuffer.CurrentSnapshot, nextCaretPosition)); } } else { // For the rest of the syntax node, // like try statement // class Bar // { // void Main() // { // tr$$y // } // } // In this case, the last close brace of 'void Main()' would be thought as a part of the try statement, // and the last close brace of 'Bar' would be thought as a part of Main() // So for these case, just find the missing open brace position and directly insert '()' to the document // 1. Find the position to insert braces. var insertionPosition = GetBraceInsertionPosition(selectedNode); // 2. Insert the braces and move caret InsertBraceAndMoveCaret(args.TextView, document, insertionPosition, cancellationToken); } } else { // Remove the braces and get the next caretPosition var (newRoot, nextCaretPosition) = RemoveBraceFromSelectedNode( document, root, selectedNode, args.TextView.Options, cancellationToken); if (document.Project.Solution.Workspace.TryApplyChanges(document.WithSyntaxRoot(newRoot).Project.Solution)) { args.TextView.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(args.SubjectBuffer.CurrentSnapshot, nextCaretPosition)); } } } private static (SyntaxNode newRoot, int nextCaretPosition) AddBraceToSelectedNode( Document document, SyntaxNode root, SyntaxNode selectedNode, IEditorOptions editorOptions, CancellationToken cancellationToken) { // For these nodes, directly modify the node and replace it. if (selectedNode is BaseTypeDeclarationSyntax or BaseMethodDeclarationSyntax or LocalFunctionStatementSyntax or FieldDeclarationSyntax or EventFieldDeclarationSyntax or AccessorDeclarationSyntax) { var newRoot = ReplaceNodeAndFormat( document, root, selectedNode, WithBraces(selectedNode, editorOptions), cancellationToken); // Locate the open brace token, and move the caret after it. var nextCaretPosition = GetOpenBraceSpanEnd(newRoot); return (newRoot, nextCaretPosition); } // For ObjectCreationExpression, like new List<int>() // It requires // 1. Add an initializer to it. // 2. make sure it has '()' after the type, and if its next token is a missing semicolon, add that semicolon. e.g // var c = new Obje$$ct() => var c = new Object(); if (selectedNode is ObjectCreationExpressionSyntax objectCreationExpressionNode) { var (newNode, oldNode) = ModifyObjectCreationExpressionNode(objectCreationExpressionNode, addOrRemoveInitializer: true, editorOptions); var newRoot = ReplaceNodeAndFormat( document, root, oldNode, newNode, cancellationToken); // Locate the open brace token, and move the caret after it. var nextCaretPosition = GetOpenBraceSpanEnd(newRoot); return (newRoot, nextCaretPosition); } // For the embeddedStatementOwner node, like ifStatement/elseClause // It requires: // 1. Add a empty block as its statement. // 2. Handle its previous statement if needed. // case 1: // if$$ (true) // var c = 10; // => // if (true) // { // $$ // } // var c = 10; // In this case, 'var c = 10;' is considered as the inner statement so we need to move it next to the if Statement // // case 2: // if (true) // { // } // else if$$ (false) // Print("Bar"); // else // { // } // => // if (true) // { // } // else if (false) // { // $$ // Print("Bar"); // } // else // { // } // In this case 'Print("Bar")' is considered as the innerStatement so when we inserted the empty block, we need also insert that if (selectedNode.IsEmbeddedStatementOwner()) { return AddBraceToEmbeddedStatementOwner(document, root, selectedNode, editorOptions, cancellationToken); } throw ExceptionUtilities.UnexpectedValue(selectedNode); } private static (SyntaxNode newRoot, int nextCaretPosition) RemoveBraceFromSelectedNode( Document document, SyntaxNode root, SyntaxNode selectedNode, IEditorOptions editorOptions, CancellationToken cancellationToken) { // Remove the initializer from ObjectCreationExpression // Step 1. Remove the initializer // e.g. var c = new Bar { $$ } => var c = new Bar // // Step 2. Add parenthesis // e.g var c = new Bar => var c = new Bar() // // Step 3. Add semicolon if needed // e.g. var c = new Bar() => var c = new Bar(); if (selectedNode is ObjectCreationExpressionSyntax objectCreationExpressionNode) { var (newNode, oldNode) = ModifyObjectCreationExpressionNode(objectCreationExpressionNode, addOrRemoveInitializer: false, editorOptions); var newRoot = ReplaceNodeAndFormat( document, root, oldNode, newNode, cancellationToken); // Find the replacement node, and move the caret to the end of line (where the last token is) var replacementNode = newRoot.GetAnnotatedNodes(s_replacementNodeAnnotation).Single(); var lastToken = replacementNode.GetLastToken(); var lineEnd = newRoot.GetText().Lines.GetLineFromPosition(lastToken.Span.End).End; return (newRoot, lineEnd); } else { // For all the other cases, include // 1. Property declaration => Field Declaration. // e.g. // class Bar // { // int Bar {$$} // } // => // class Bar // { // int Bar; // } // 2. Event Declaration => Event Field Declaration // class Bar // { // event EventHandler e { $$ } // } // => // class Bar // { // event EventHandler e; // } // 3. Accessor // class Bar // { // int Bar // { // get { $$ } // } // } // => // class Bar // { // int Bar // { // get; // } // } // Get its no-brace version of node and insert it into the root. var newRoot = ReplaceNodeAndFormat( document, root, selectedNode, WithoutBraces(selectedNode), cancellationToken); // Locate the replacement node, move the caret to the end. // e.g. // class Bar // { // event EventHandler e { $$ } // } // => // class Bar // { // event EventHandler e;$$ // } // and we need to move the caret after semicolon var nextCaretPosition = newRoot.GetAnnotatedNodes(s_replacementNodeAnnotation).Single().GetLastToken().Span.End; return (newRoot, nextCaretPosition); } } private static int GetOpenBraceSpanEnd(SyntaxNode root) { // Use the annotation to find the end of the open brace. var annotatedOpenBraceToken = root.GetAnnotatedTokens(s_openBracePositionAnnotation).Single(); return annotatedOpenBraceToken.Span.End; } private static int GetBraceInsertionPosition(SyntaxNode node) => node switch { NamespaceDeclarationSyntax => node.GetBraces().openBrace.SpanStart, IndexerDeclarationSyntax indexerNode => indexerNode.ParameterList.Span.End, SwitchStatementSyntax switchStatementNode => switchStatementNode.CloseParenToken.Span.End, TryStatementSyntax tryStatementNode => tryStatementNode.TryKeyword.Span.End, CatchClauseSyntax catchClauseNode => catchClauseNode.Block.SpanStart, FinallyClauseSyntax finallyClauseNode => finallyClauseNode.Block.SpanStart, _ => throw ExceptionUtilities.Unreachable, }; private static string GetBracePairString(IEditorOptions editorOptions) => string.Concat(SyntaxFacts.GetText(SyntaxKind.OpenBraceToken), editorOptions.GetNewLineCharacter(), SyntaxFacts.GetText(SyntaxKind.CloseBraceToken)); private void InsertBraceAndMoveCaret( ITextView textView, Document document, int insertionPosition, CancellationToken cancellationToken) { var bracePair = GetBracePairString(textView.Options); // 1. Insert { }. var newDocument = document.InsertText(insertionPosition, bracePair, cancellationToken); // 2. Place caret between the braces. textView.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(textView.TextSnapshot, insertionPosition + 1)); // 3. Format the document using the close brace. FormatAndApplyBasedOnEndToken(newDocument, insertionPosition + bracePair.Length - 1, cancellationToken); } protected override (SyntaxNode selectedNode, bool addBrace)? GetValidNodeToModifyBraces(Document document, int caretPosition, CancellationToken cancellationToken) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var token = root.FindTokenOnLeftOfPosition(caretPosition); if (token.IsKind(SyntaxKind.None)) { return null; } foreach (var node in token.GetAncestors<SyntaxNode>()) { if (ShouldAddBraces(node, caretPosition)) { return (selectedNode: node, addBrace: true); } if (ShouldRemoveBraces(node, caretPosition)) { return (selectedNode: node, addBrace: false); } } return null; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion { /// <summary> /// csharp automatic line ender command handler /// </summary> [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(PredefinedCommandHandlerNames.AutomaticLineEnder)] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] internal partial class AutomaticLineEnderCommandHandler : AbstractAutomaticLineEnderCommandHandler { private static readonly string s_semicolon = SyntaxFacts.GetText(SyntaxKind.SemicolonToken); /// <summary> /// Annotation to locate the open brace token. /// </summary> private static readonly SyntaxAnnotation s_openBracePositionAnnotation = new(); /// <summary> /// Annotation to locate the replacement node(with or without braces). /// </summary> private static readonly SyntaxAnnotation s_replacementNodeAnnotation = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AutomaticLineEnderCommandHandler( ITextUndoHistoryRegistry undoRegistry, IEditorOperationsFactoryService editorOperations) : base(undoRegistry, editorOperations) { } protected override void NextAction(IEditorOperations editorOperation, Action nextAction) => editorOperation.InsertNewLine(); protected override bool TreatAsReturn(Document document, int caretPosition, CancellationToken cancellationToken) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var endToken = root.FindToken(caretPosition); if (endToken.IsMissing) { return false; } var tokenToLeft = root.FindTokenOnLeftOfPosition(caretPosition); var startToken = endToken.GetPreviousToken(); // case 1: // Consider code like so: try {|} // With auto brace completion on, user types `{` and `Return` in a hurry. // During typing, it is possible that shift was still down and not released after typing `{`. // So we've got an unintentional `shift + enter` and also we have nothing to complete this, // so we put in a newline, // which generates code like so : try { } // | // which is not useful as : try { // | // } // To support this, we treat `shift + enter` like `enter` here. var afterOpenBrace = startToken.Kind() == SyntaxKind.OpenBraceToken && endToken.Kind() == SyntaxKind.CloseBraceToken && tokenToLeft == startToken && endToken.Parent.IsKind(SyntaxKind.Block) && FormattingRangeHelper.AreTwoTokensOnSameLine(startToken, endToken); return afterOpenBrace; } protected override Document FormatAndApplyBasedOnEndToken(Document document, int position, CancellationToken cancellationToken) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var endToken = root.FindToken(position); var span = GetFormattedTextSpan(root, endToken); if (span == null) { return document; } var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var changes = Formatter.GetFormattedTextChanges( root, SpecializedCollections.SingletonCollection(CommonFormattingHelpers.GetFormattingSpan(root, span.Value)), document.Project.Solution.Workspace, options, cancellationToken: cancellationToken); return document.ApplyTextChanges(changes, cancellationToken); } private static TextSpan? GetFormattedTextSpan(SyntaxNode root, SyntaxToken endToken) { if (endToken.IsMissing) { return null; } var ranges = FormattingRangeHelper.FindAppropriateRange(endToken, useDefaultRange: false); if (ranges == null) { return null; } var startToken = ranges.Value.Item1; if (startToken.IsMissing || startToken.Kind() == SyntaxKind.None) { return null; } return CommonFormattingHelpers.GetFormattingSpan(root, TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End)); } #region SemicolonAppending protected override string? GetEndingString(Document document, int position, CancellationToken cancellationToken) { // prepare expansive information from document var tree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var root = tree.GetRoot(cancellationToken); var text = tree.GetText(cancellationToken); // Go through the set of owning nodes in leaf to root chain. foreach (var owningNode in GetOwningNodes(root, position)) { if (!TryGetLastToken(text, position, owningNode, out var lastToken)) { // If we can't get last token, there is nothing more to do, just skip // the other owning nodes and return. return null; } if (!CheckLocation(text, position, owningNode, lastToken)) { // If we failed this check, we indeed got the intended owner node and // inserting line ender here would introduce errors. return null; } // so far so good. we only add semi-colon if it makes statement syntax error free var textToParse = owningNode.NormalizeWhitespace().ToFullString() + s_semicolon; // currently, Parsing a field is not supported. as a workaround, wrap the field in a type and parse var node = ParseNode(tree, owningNode, textToParse); // Insert line ender if we didn't introduce any diagnostics, if not try the next owning node. if (node != null && !node.ContainsDiagnostics) { return s_semicolon; } } return null; } private static SyntaxNode? ParseNode(SyntaxTree tree, SyntaxNode owningNode, string textToParse) => owningNode switch { BaseFieldDeclarationSyntax => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options), BaseMethodDeclarationSyntax => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options), BasePropertyDeclarationSyntax => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options), StatementSyntax => SyntaxFactory.ParseStatement(textToParse, options: (CSharpParseOptions)tree.Options), UsingDirectiveSyntax => SyntaxFactory.ParseCompilationUnit(textToParse, options: (CSharpParseOptions)tree.Options), _ => null, }; /// <summary> /// wrap field in type /// </summary> private static string WrapInType(string textToParse) => "class C { " + textToParse + " }"; /// <summary> /// make sure current location is okay to put semicolon /// </summary> private static bool CheckLocation(SourceText text, int position, SyntaxNode owningNode, SyntaxToken lastToken) { var line = text.Lines.GetLineFromPosition(position); // if caret is at the end of the line and containing statement is expression statement // don't do anything if (position == line.End && owningNode is ExpressionStatementSyntax) { return false; } var locatedAtTheEndOfLine = LocatedAtTheEndOfLine(line, lastToken); // make sure that there is no trailing text after last token on the line if it is not at the end of the line if (!locatedAtTheEndOfLine) { var endingString = text.ToString(TextSpan.FromBounds(lastToken.Span.End, line.End)); if (!string.IsNullOrWhiteSpace(endingString)) { return false; } } // check whether using has contents if (owningNode is UsingDirectiveSyntax u && u.Name.IsMissing) { return false; } // make sure there is no open string literals var previousToken = lastToken.GetPreviousToken(); if (previousToken.Kind() == SyntaxKind.StringLiteralToken && previousToken.ToString().Last() != '"') { return false; } if (previousToken.Kind() == SyntaxKind.CharacterLiteralToken && previousToken.ToString().Last() != '\'') { return false; } // now, check embedded statement case if (owningNode.IsEmbeddedStatementOwner()) { var embeddedStatement = owningNode.GetEmbeddedStatement(); if (embeddedStatement == null || embeddedStatement.Span.IsEmpty) { return false; } } return true; } /// <summary> /// get last token of the given using/field/statement/expression bodied member if one exists /// </summary> private static bool TryGetLastToken(SourceText text, int position, SyntaxNode owningNode, out SyntaxToken lastToken) { lastToken = owningNode.GetLastToken(includeZeroWidth: true); // last token must be on the same line as the caret var line = text.Lines.GetLineFromPosition(position); var locatedAtTheEndOfLine = LocatedAtTheEndOfLine(line, lastToken); if (!locatedAtTheEndOfLine && text.Lines.IndexOf(lastToken.Span.End) != line.LineNumber) { return false; } // if we already have last semicolon, we don't need to do anything if (!lastToken.IsMissing && lastToken.Kind() == SyntaxKind.SemicolonToken) { return false; } return true; } /// <summary> /// check whether the line is located at the end of the line /// </summary> private static bool LocatedAtTheEndOfLine(TextLine line, SyntaxToken lastToken) => lastToken.IsMissing && lastToken.Span.End == line.EndIncludingLineBreak; /// <summary> /// find owning usings/field/statement/expression-bodied member of the given position /// </summary> private static IEnumerable<SyntaxNode> GetOwningNodes(SyntaxNode root, int position) { // make sure caret position is somewhere we can find a token var token = root.FindTokenFromEnd(position); if (token.Kind() == SyntaxKind.None) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } return token.GetAncestors<SyntaxNode>() .Where(AllowedConstructs) .Select(OwningNode) .WhereNotNull(); } private static bool AllowedConstructs(SyntaxNode n) => n is StatementSyntax or BaseFieldDeclarationSyntax or UsingDirectiveSyntax or ArrowExpressionClauseSyntax; private static SyntaxNode? OwningNode(SyntaxNode n) => n is ArrowExpressionClauseSyntax ? n.Parent : n; #endregion #region BraceModification protected override void ModifySelectedNode( AutomaticLineEnderCommandArgs args, Document document, SyntaxNode selectedNode, bool addBrace, int caretPosition, CancellationToken cancellationToken) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); // Add braces for the selected node if (addBrace) { // For these syntax node, braces pair could be easily added by modify the syntax tree if (selectedNode is BaseTypeDeclarationSyntax or BaseMethodDeclarationSyntax or LocalFunctionStatementSyntax or FieldDeclarationSyntax or EventFieldDeclarationSyntax or AccessorDeclarationSyntax or ObjectCreationExpressionSyntax or WhileStatementSyntax or ForEachStatementSyntax or ForStatementSyntax or LockStatementSyntax or UsingStatementSyntax or DoStatementSyntax or IfStatementSyntax or ElseClauseSyntax) { // Add the braces and get the next caretPosition var (newRoot, nextCaretPosition) = AddBraceToSelectedNode(document, root, selectedNode, args.TextView.Options, cancellationToken); if (document.Project.Solution.Workspace.TryApplyChanges(document.WithSyntaxRoot(newRoot).Project.Solution)) { args.TextView.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(args.SubjectBuffer.CurrentSnapshot, nextCaretPosition)); } } else { // For the rest of the syntax node, // like try statement // class Bar // { // void Main() // { // tr$$y // } // } // In this case, the last close brace of 'void Main()' would be thought as a part of the try statement, // and the last close brace of 'Bar' would be thought as a part of Main() // So for these case, just find the missing open brace position and directly insert '()' to the document // 1. Find the position to insert braces. var insertionPosition = GetBraceInsertionPosition(selectedNode); // 2. Insert the braces and move caret InsertBraceAndMoveCaret(args.TextView, document, insertionPosition, cancellationToken); } } else { // Remove the braces and get the next caretPosition var (newRoot, nextCaretPosition) = RemoveBraceFromSelectedNode( document, root, selectedNode, args.TextView.Options, cancellationToken); if (document.Project.Solution.Workspace.TryApplyChanges(document.WithSyntaxRoot(newRoot).Project.Solution)) { args.TextView.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(args.SubjectBuffer.CurrentSnapshot, nextCaretPosition)); } } } private static (SyntaxNode newRoot, int nextCaretPosition) AddBraceToSelectedNode( Document document, SyntaxNode root, SyntaxNode selectedNode, IEditorOptions editorOptions, CancellationToken cancellationToken) { // For these nodes, directly modify the node and replace it. if (selectedNode is BaseTypeDeclarationSyntax or BaseMethodDeclarationSyntax or LocalFunctionStatementSyntax or FieldDeclarationSyntax or EventFieldDeclarationSyntax or AccessorDeclarationSyntax) { var newRoot = ReplaceNodeAndFormat( document, root, selectedNode, WithBraces(selectedNode, editorOptions), cancellationToken); // Locate the open brace token, and move the caret after it. var nextCaretPosition = GetOpenBraceSpanEnd(newRoot); return (newRoot, nextCaretPosition); } // For ObjectCreationExpression, like new List<int>() // It requires // 1. Add an initializer to it. // 2. make sure it has '()' after the type, and if its next token is a missing semicolon, add that semicolon. e.g // var c = new Obje$$ct() => var c = new Object(); if (selectedNode is ObjectCreationExpressionSyntax objectCreationExpressionNode) { var (newNode, oldNode) = ModifyObjectCreationExpressionNode(objectCreationExpressionNode, addOrRemoveInitializer: true, editorOptions); var newRoot = ReplaceNodeAndFormat( document, root, oldNode, newNode, cancellationToken); // Locate the open brace token, and move the caret after it. var nextCaretPosition = GetOpenBraceSpanEnd(newRoot); return (newRoot, nextCaretPosition); } // For the embeddedStatementOwner node, like ifStatement/elseClause // It requires: // 1. Add a empty block as its statement. // 2. Handle its previous statement if needed. // case 1: // if$$ (true) // var c = 10; // => // if (true) // { // $$ // } // var c = 10; // In this case, 'var c = 10;' is considered as the inner statement so we need to move it next to the if Statement // // case 2: // if (true) // { // } // else if$$ (false) // Print("Bar"); // else // { // } // => // if (true) // { // } // else if (false) // { // $$ // Print("Bar"); // } // else // { // } // In this case 'Print("Bar")' is considered as the innerStatement so when we inserted the empty block, we need also insert that if (selectedNode.IsEmbeddedStatementOwner()) { return AddBraceToEmbeddedStatementOwner(document, root, selectedNode, editorOptions, cancellationToken); } throw ExceptionUtilities.UnexpectedValue(selectedNode); } private static (SyntaxNode newRoot, int nextCaretPosition) RemoveBraceFromSelectedNode( Document document, SyntaxNode root, SyntaxNode selectedNode, IEditorOptions editorOptions, CancellationToken cancellationToken) { // Remove the initializer from ObjectCreationExpression // Step 1. Remove the initializer // e.g. var c = new Bar { $$ } => var c = new Bar // // Step 2. Add parenthesis // e.g var c = new Bar => var c = new Bar() // // Step 3. Add semicolon if needed // e.g. var c = new Bar() => var c = new Bar(); if (selectedNode is ObjectCreationExpressionSyntax objectCreationExpressionNode) { var (newNode, oldNode) = ModifyObjectCreationExpressionNode(objectCreationExpressionNode, addOrRemoveInitializer: false, editorOptions); var newRoot = ReplaceNodeAndFormat( document, root, oldNode, newNode, cancellationToken); // Find the replacement node, and move the caret to the end of line (where the last token is) var replacementNode = newRoot.GetAnnotatedNodes(s_replacementNodeAnnotation).Single(); var lastToken = replacementNode.GetLastToken(); var lineEnd = newRoot.GetText().Lines.GetLineFromPosition(lastToken.Span.End).End; return (newRoot, lineEnd); } else { // For all the other cases, include // 1. Property declaration => Field Declaration. // e.g. // class Bar // { // int Bar {$$} // } // => // class Bar // { // int Bar; // } // 2. Event Declaration => Event Field Declaration // class Bar // { // event EventHandler e { $$ } // } // => // class Bar // { // event EventHandler e; // } // 3. Accessor // class Bar // { // int Bar // { // get { $$ } // } // } // => // class Bar // { // int Bar // { // get; // } // } // Get its no-brace version of node and insert it into the root. var newRoot = ReplaceNodeAndFormat( document, root, selectedNode, WithoutBraces(selectedNode), cancellationToken); // Locate the replacement node, move the caret to the end. // e.g. // class Bar // { // event EventHandler e { $$ } // } // => // class Bar // { // event EventHandler e;$$ // } // and we need to move the caret after semicolon var nextCaretPosition = newRoot.GetAnnotatedNodes(s_replacementNodeAnnotation).Single().GetLastToken().Span.End; return (newRoot, nextCaretPosition); } } private static int GetOpenBraceSpanEnd(SyntaxNode root) { // Use the annotation to find the end of the open brace. var annotatedOpenBraceToken = root.GetAnnotatedTokens(s_openBracePositionAnnotation).Single(); return annotatedOpenBraceToken.Span.End; } private static int GetBraceInsertionPosition(SyntaxNode node) { if (node is SwitchStatementSyntax switchStatementNode) { // There is no parenthesis pair in the switchStatementNode, and the node before 'switch' is an expression // e.g. // void Foo(int i) // { // var c = (i + 1) swit$$ch // } // Consider this as a SwitchExpression, add the brace after 'switch' if (switchStatementNode.OpenParenToken.IsMissing && switchStatementNode.CloseParenToken.IsMissing && IsTokenPartOfExpresion(switchStatementNode.GetFirstToken().GetPreviousToken())) { return switchStatementNode.SwitchKeyword.Span.End; } // In all other case, think it is a switch statement, add brace after the close parenthesis. return switchStatementNode.CloseParenToken.Span.End; } return node switch { NamespaceDeclarationSyntax => node.GetBraces().openBrace.SpanStart, IndexerDeclarationSyntax indexerNode => indexerNode.ParameterList.Span.End, TryStatementSyntax tryStatementNode => tryStatementNode.TryKeyword.Span.End, CatchClauseSyntax catchClauseNode => catchClauseNode.Block.SpanStart, FinallyClauseSyntax finallyClauseNode => finallyClauseNode.Block.SpanStart, _ => throw ExceptionUtilities.Unreachable, }; } private static bool IsTokenPartOfExpresion(SyntaxToken syntaxToken) { if (syntaxToken.IsMissing || syntaxToken.IsKind(SyntaxKind.None)) { return false; } return !syntaxToken.GetAncestors<ExpressionSyntax>().IsEmpty(); } private static string GetBracePairString(IEditorOptions editorOptions) => string.Concat(SyntaxFacts.GetText(SyntaxKind.OpenBraceToken), editorOptions.GetNewLineCharacter(), SyntaxFacts.GetText(SyntaxKind.CloseBraceToken)); private void InsertBraceAndMoveCaret( ITextView textView, Document document, int insertionPosition, CancellationToken cancellationToken) { var bracePair = GetBracePairString(textView.Options); // 1. Insert { }. var newDocument = document.InsertText(insertionPosition, bracePair, cancellationToken); // 2. Place caret between the braces. textView.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(textView.TextSnapshot, insertionPosition + 1)); // 3. Format the document using the close brace. FormatAndApplyBasedOnEndToken(newDocument, insertionPosition + bracePair.Length - 1, cancellationToken); } protected override (SyntaxNode selectedNode, bool addBrace)? GetValidNodeToModifyBraces(Document document, int caretPosition, CancellationToken cancellationToken) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var token = root.FindTokenOnLeftOfPosition(caretPosition); if (token.IsKind(SyntaxKind.None)) { return null; } foreach (var node in token.GetAncestors<SyntaxNode>()) { if (ShouldAddBraces(node, caretPosition)) { return (selectedNode: node, addBrace: true); } if (ShouldRemoveBraces(node, caretPosition)) { return (selectedNode: node, addBrace: false); } } return null; } #endregion } }
1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler_Helpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion { internal partial class AutomaticLineEnderCommandHandler { #region NodeReplacementHelpers private static (SyntaxNode newRoot, int nextCaretPosition) ReplaceStatementOwnerAndInsertStatement( Document document, SyntaxNode root, SyntaxNode oldNode, SyntaxNode newNode, SyntaxNode anchorNode, ImmutableArray<StatementSyntax> nodesToInsert, CancellationToken cancellationToken) { var rootEditor = new SyntaxEditor(root, document.Project.Solution.Workspace); // 1. Insert the node before anchor node rootEditor.InsertAfter(anchorNode, nodesToInsert); // 2. Replace the old node with newNode. (new node is the node with correct braces) rootEditor.ReplaceNode(oldNode, newNode.WithAdditionalAnnotations(s_replacementNodeAnnotation)); var newRoot = rootEditor.GetChangedRoot(); // 4. Format the new node so that the inserted braces/blocks would have correct indentation and formatting. var newNodeAfterInsertion = newRoot.GetAnnotatedNodes(s_replacementNodeAnnotation).Single(); var formattedNewRoot = Formatter.Format( newRoot, newNodeAfterInsertion.Span, document.Project.Solution.Workspace, cancellationToken: cancellationToken); // 4. Use the annotation to find the end of the open brace, it would be the new caret position var nextCaretPosition = formattedNewRoot.GetAnnotatedTokens(s_openBracePositionAnnotation).Single().Span.End; return (formattedNewRoot, nextCaretPosition); } private static SyntaxNode ReplaceNodeAndFormat( Document document, SyntaxNode root, SyntaxNode oldNode, SyntaxNode newNode, CancellationToken cancellationToken) { // 1. Tag the new node so that it could be found later. var annotatedNewNode = newNode.WithAdditionalAnnotations(s_replacementNodeAnnotation); // 2. Replace the old node with newNode. (new node is the node with correct braces) var newRoot = root.ReplaceNode( oldNode, annotatedNewNode); // 3. Find the newNode in the new syntax root. var newNodeAfterInsertion = newRoot.GetAnnotatedNodes(s_replacementNodeAnnotation).Single(); // 4. Format the new node so that the inserted braces/blocks would have correct indentation and formatting. var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var formattedNewRoot = Formatter.Format( newRoot, newNodeAfterInsertion.Span, document.Project.Solution.Workspace, options, cancellationToken: cancellationToken); return formattedNewRoot; } #endregion #region EmbeddedStatementModificationHelpers private static (SyntaxNode newRoot, int nextCaretPosition) AddBraceToEmbeddedStatementOwner( Document document, SyntaxNode root, SyntaxNode embeddedStatementOwner, IEditorOptions editorOptions, CancellationToken cancellationToken) { // If there is no inner statement, just add an empty block to it. // e.g. // class Bar // { // if (true)$$ // } // => // class Bar // { // if (true) // { // } // } var statement = embeddedStatementOwner.GetEmbeddedStatement(); if (statement == null || statement.IsMissing) { var newRoot = ReplaceNodeAndFormat( document, root, embeddedStatementOwner, WithBraces(embeddedStatementOwner, editorOptions), cancellationToken); // Locate the open brace token, and move the caret after it. var nextCaretPosition = GetOpenBraceSpanEnd(newRoot); return (newRoot, nextCaretPosition); } // There is an inner statement, it needs to be handled differently in addition to adding the block, // For while, ForEach, Lock and Using statement, // If there is an statement in the embeddedStatementOwner, // move the old statement next to the statementOwner, // and insert a empty block into the statementOwner, // e.g. // before: // whi$$le(true) // var i = 1; // for this case 'var i = 1;' is thought as the inner statement, // // after: // while(true) // { // $$ // } // var i = 1; return embeddedStatementOwner switch { WhileStatementSyntax or ForEachStatementSyntax or ForStatementSyntax or LockStatementSyntax or UsingStatementSyntax => ReplaceStatementOwnerAndInsertStatement( document, root, oldNode: embeddedStatementOwner, newNode: AddBlockToEmbeddedStatementOwner(embeddedStatementOwner, editorOptions), anchorNode: embeddedStatementOwner, nodesToInsert: ImmutableArray<StatementSyntax>.Empty.Add(statement), cancellationToken), DoStatementSyntax doStatementNode => AddBraceToDoStatement(document, root, doStatementNode, editorOptions, statement, cancellationToken), IfStatementSyntax ifStatementNode => AddBraceToIfStatement(document, root, ifStatementNode, editorOptions, statement, cancellationToken), ElseClauseSyntax elseClauseNode => AddBraceToElseClause(document, root, elseClauseNode, editorOptions, statement, cancellationToken), _ => throw ExceptionUtilities.UnexpectedValue(embeddedStatementOwner), }; } private static (SyntaxNode newRoot, int nextCaretPosition) AddBraceToDoStatement( Document document, SyntaxNode root, DoStatementSyntax doStatementNode, IEditorOptions editorOptions, StatementSyntax innerStatement, CancellationToken cancellationToken) { // If this do statement doesn't end with the 'while' parts // e.g: // before: // d$$o // Print("hello"); // after: // do // { // $$ // } // Print("hello"); if (doStatementNode.WhileKeyword.IsMissing && doStatementNode.SemicolonToken.IsMissing && doStatementNode.OpenParenToken.IsMissing && doStatementNode.CloseParenToken.IsMissing) { return ReplaceStatementOwnerAndInsertStatement( document, root, oldNode: doStatementNode, newNode: AddBlockToEmbeddedStatementOwner(doStatementNode, editorOptions), anchorNode: doStatementNode, nodesToInsert: ImmutableArray<StatementSyntax>.Empty.Add(innerStatement), cancellationToken); } // if the do statement has 'while' as an end // e.g: // before: // d$$o // Print("hello"); // while (true); // after: // do // { // $$ // Print("hello"); // } while(true); var newRoot = ReplaceNodeAndFormat( document, root, doStatementNode, AddBlockToEmbeddedStatementOwner(doStatementNode, editorOptions, innerStatement), cancellationToken); var nextCaretPosition = GetOpenBraceSpanEnd(newRoot); return (newRoot, nextCaretPosition); } private static (SyntaxNode newRoot, int nextCaretPosition) AddBraceToIfStatement( Document document, SyntaxNode root, IfStatementSyntax ifStatementNode, IEditorOptions editorOptions, StatementSyntax innerStatement, CancellationToken cancellationToken) { // This ifStatement doesn't have an else clause, and its parent is a Block. // Insert the innerStatement next to the ifStatement // e.g. // if ($$a) // Print(); // => // if (a) // { // $$ // } // Print(); if (ifStatementNode.Else == null && ifStatementNode.Parent is BlockSyntax) { return ReplaceStatementOwnerAndInsertStatement(document, root, ifStatementNode, AddBlockToEmbeddedStatementOwner(ifStatementNode, editorOptions), ifStatementNode, ImmutableArray<StatementSyntax>.Empty.Add(innerStatement), cancellationToken); } // If this IfStatement has an else statement after // e.g. // before: // if $$(true) // print("Hello"); // else {} // after: // if (true) // { // $$ // print("Hello"); // } // else {} var newRoot = ReplaceNodeAndFormat( document, root, ifStatementNode, AddBlockToEmbeddedStatementOwner(ifStatementNode, editorOptions, innerStatement), cancellationToken); var nextCaretPosition = GetOpenBraceSpanEnd(newRoot); return (newRoot, nextCaretPosition); } private static (SyntaxNode newRoot, int nextCaretPosition) AddBraceToElseClause( Document document, SyntaxNode root, ElseClauseSyntax elseClauseNode, IEditorOptions editorOptions, StatementSyntax innerStatement, CancellationToken cancellationToken) { // If this is an 'els$$e if(true)' statement, // then treat it as the selected node is the nested if statement if (elseClauseNode.Statement is IfStatementSyntax) { return AddBraceToEmbeddedStatementOwner(document, root, elseClauseNode.Statement, editorOptions, cancellationToken); } // Otherwise, it is just an ending else clause. // if its parent is an ifStatement and the parent of ifStatement is a block, insert the innerStatement after the ifStatement // e.g. before: // if (true) // { // } els$$e // Print(); // after: // if (true) // { // } els$$e // { // $$ // } // Print(); if (elseClauseNode.Parent is IfStatementSyntax { Parent: BlockSyntax }) { return ReplaceStatementOwnerAndInsertStatement(document, root, elseClauseNode, WithBraces(elseClauseNode, editorOptions), elseClauseNode.Parent!, ImmutableArray<StatementSyntax>.Empty.Add(innerStatement), cancellationToken); } // For all the other cases, // Put the innerStatement into the block // e.g. // if (a) // if (true) // { // } // else // { // $$ // Print(); // } // => // if (a) // if (true) // { // } // els$$e // Print(); var formattedNewRoot = ReplaceNodeAndFormat( document, root, elseClauseNode, AddBlockToEmbeddedStatementOwner(elseClauseNode, editorOptions, innerStatement), cancellationToken); var nextCaretPosition = formattedNewRoot.GetAnnotatedTokens(s_openBracePositionAnnotation).Single().Span.End; return (formattedNewRoot, nextCaretPosition); } #endregion #region ObjectCreationExpressionModificationHelpers private static (SyntaxNode newNode, SyntaxNode oldNode) ModifyObjectCreationExpressionNode( ObjectCreationExpressionSyntax objectCreationExpressionNode, bool addOrRemoveInitializer, IEditorOptions editorOptions) { // 1. Add '()' after the type. // e.g. var c = new Bar => var c = new Bar() var objectCreationNodeWithArgumentList = WithArgumentListIfNeeded(objectCreationExpressionNode); // 2. Add or remove initializer // e.g. var c = new Bar() => var c = new Bar() { } var objectCreationNodeWithCorrectInitializer = addOrRemoveInitializer ? WithBraces(objectCreationNodeWithArgumentList, editorOptions) : WithoutBraces(objectCreationNodeWithArgumentList); // 3. Handler the semicolon. // If the next token is a semicolon, e.g. // var l = new Ba$$r() { } => var l = new Ba$$r() { }; var nextToken = objectCreationExpressionNode.GetLastToken(includeZeroWidth: true).GetNextToken(includeZeroWidth: true); if (nextToken.IsKind(SyntaxKind.SemicolonToken) && nextToken.Parent != null && nextToken.Parent.Contains(objectCreationExpressionNode)) { var objectCreationNodeContainer = nextToken.Parent; // Replace the old object creation node and add the semicolon token. // Note: need to move the trailing trivia of the objectCreationExpressionNode after the semicolon token // e.g. // var l = new Bar() {} // I am some comments // => // var l = new Bar() {}; // I am some comments var replacementContainerNode = objectCreationNodeContainer.ReplaceSyntax( nodes: SpecializedCollections.SingletonCollection(objectCreationExpressionNode), (_, _) => objectCreationNodeWithCorrectInitializer.WithoutTrailingTrivia(), tokens: SpecializedCollections.SingletonCollection(nextToken), computeReplacementToken: (_, _) => SyntaxFactory.Token(SyntaxKind.SemicolonToken).WithTrailingTrivia(objectCreationNodeWithCorrectInitializer.GetTrailingTrivia()), trivia: Enumerable.Empty<SyntaxTrivia>(), computeReplacementTrivia: (_, syntaxTrivia) => syntaxTrivia); return (replacementContainerNode, objectCreationNodeContainer); } else { // No need to change the semicolon, just return the objectCreationExpression with correct initializer return (objectCreationNodeWithCorrectInitializer, objectCreationExpressionNode); } } /// <summary> /// Add argument list to the objectCreationExpression if needed. /// e.g. new Bar; => new Bar(); /// </summary> private static ObjectCreationExpressionSyntax WithArgumentListIfNeeded(ObjectCreationExpressionSyntax objectCreationExpressionNode) { var argumentList = objectCreationExpressionNode.ArgumentList; var hasArgumentList = argumentList != null && !argumentList.IsMissing; if (!hasArgumentList) { // Make sure the trailing trivia is passed to the argument list // like var l = new List\r\n => // var l = new List()\r\r var typeNode = objectCreationExpressionNode.Type; var newArgumentList = SyntaxFactory.ArgumentList().WithTrailingTrivia(typeNode.GetTrailingTrivia()); var newTypeNode = typeNode.WithoutTrivia(); return objectCreationExpressionNode.WithType(newTypeNode).WithArgumentList(newArgumentList); } return objectCreationExpressionNode; } #endregion #region ShouldAddBraceCheck private static bool ShouldAddBraces(SyntaxNode node, int caretPosition) => node switch { NamespaceDeclarationSyntax namespaceDeclarationNode => ShouldAddBraceForNamespaceDeclaration(namespaceDeclarationNode, caretPosition), BaseTypeDeclarationSyntax baseTypeDeclarationNode => ShouldAddBraceForBaseTypeDeclaration(baseTypeDeclarationNode, caretPosition), BaseMethodDeclarationSyntax baseMethodDeclarationNode => ShouldAddBraceForBaseMethodDeclaration(baseMethodDeclarationNode, caretPosition), LocalFunctionStatementSyntax localFunctionStatementNode => ShouldAddBraceForLocalFunctionStatement(localFunctionStatementNode, caretPosition), ObjectCreationExpressionSyntax objectCreationExpressionNode => ShouldAddBraceForObjectCreationExpression(objectCreationExpressionNode), BaseFieldDeclarationSyntax baseFieldDeclarationNode => ShouldAddBraceForBaseFieldDeclaration(baseFieldDeclarationNode), AccessorDeclarationSyntax accessorDeclarationNode => ShouldAddBraceForAccessorDeclaration(accessorDeclarationNode), IndexerDeclarationSyntax indexerDeclarationNode => ShouldAddBraceForIndexerDeclaration(indexerDeclarationNode, caretPosition), SwitchStatementSyntax switchStatementNode => ShouldAddBraceForSwitchStatement(switchStatementNode), TryStatementSyntax tryStatementNode => ShouldAddBraceForTryStatement(tryStatementNode, caretPosition), CatchClauseSyntax catchClauseNode => ShouldAddBraceForCatchClause(catchClauseNode, caretPosition), FinallyClauseSyntax finallyClauseNode => ShouldAddBraceForFinallyClause(finallyClauseNode, caretPosition), DoStatementSyntax doStatementNode => ShouldAddBraceForDoStatement(doStatementNode, caretPosition), CommonForEachStatementSyntax commonForEachStatementNode => ShouldAddBraceForCommonForEachStatement(commonForEachStatementNode, caretPosition), ForStatementSyntax forStatementNode => ShouldAddBraceForForStatement(forStatementNode, caretPosition), IfStatementSyntax ifStatementNode => ShouldAddBraceForIfStatement(ifStatementNode, caretPosition), ElseClauseSyntax elseClauseNode => ShouldAddBraceForElseClause(elseClauseNode, caretPosition), LockStatementSyntax lockStatementNode => ShouldAddBraceForLockStatement(lockStatementNode, caretPosition), UsingStatementSyntax usingStatementNode => ShouldAddBraceForUsingStatement(usingStatementNode, caretPosition), WhileStatementSyntax whileStatementNode => ShouldAddBraceForWhileStatement(whileStatementNode, caretPosition), _ => false, }; /// <summary> /// For namespace, make sure it has name there is no braces /// </summary> private static bool ShouldAddBraceForNamespaceDeclaration(NamespaceDeclarationSyntax namespaceDeclarationNode, int caretPosition) => !namespaceDeclarationNode.Name.IsMissing && HasNoBrace(namespaceDeclarationNode) && !WithinAttributeLists(namespaceDeclarationNode, caretPosition) && !WithinBraces(namespaceDeclarationNode, caretPosition); /// <summary> /// For class/struct/enum ..., make sure it has name and there is no braces. /// </summary> private static bool ShouldAddBraceForBaseTypeDeclaration(BaseTypeDeclarationSyntax baseTypeDeclarationNode, int caretPosition) => !baseTypeDeclarationNode.Identifier.IsMissing && HasNoBrace(baseTypeDeclarationNode) && !WithinAttributeLists(baseTypeDeclarationNode, caretPosition) && !WithinBraces(baseTypeDeclarationNode, caretPosition); /// <summary> /// For method, make sure it has a ParameterList, because later braces would be inserted after the Parameterlist /// </summary> private static bool ShouldAddBraceForBaseMethodDeclaration(BaseMethodDeclarationSyntax baseMethodDeclarationNode, int caretPosition) => baseMethodDeclarationNode.ExpressionBody == null && baseMethodDeclarationNode.Body == null && !baseMethodDeclarationNode.ParameterList.IsMissing && baseMethodDeclarationNode.SemicolonToken.IsMissing && !WithinAttributeLists(baseMethodDeclarationNode, caretPosition) && !WithinMethodBody(baseMethodDeclarationNode, caretPosition) // Make sure we don't insert braces for method in Interface. && !baseMethodDeclarationNode.IsParentKind(SyntaxKind.InterfaceDeclaration); /// <summary> /// For local Function, make sure it has a ParameterList, because later braces would be inserted after the Parameterlist /// </summary> private static bool ShouldAddBraceForLocalFunctionStatement(LocalFunctionStatementSyntax localFunctionStatementNode, int caretPosition) => localFunctionStatementNode.ExpressionBody == null && localFunctionStatementNode.Body == null && !localFunctionStatementNode.ParameterList.IsMissing && !WithinAttributeLists(localFunctionStatementNode, caretPosition) && !WithinMethodBody(localFunctionStatementNode, caretPosition); /// <summary> /// Add brace for ObjectCreationExpression if it doesn't have initializer /// </summary> private static bool ShouldAddBraceForObjectCreationExpression(ObjectCreationExpressionSyntax objectCreationExpressionNode) => objectCreationExpressionNode.Initializer == null; /// <summary> /// Add braces for field and event field if they only have one variable, semicolon is missing and don't have readonly keyword /// Example: /// public int Bar$$ => /// public int Bar /// { /// $$ /// } /// This would change field to property, and change event field to event declaration. /// </summary> private static bool ShouldAddBraceForBaseFieldDeclaration(BaseFieldDeclarationSyntax baseFieldDeclarationNode) => baseFieldDeclarationNode.Declaration.Variables.Count == 1 && baseFieldDeclarationNode.Declaration.Variables[0].Initializer == null && !baseFieldDeclarationNode.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) && baseFieldDeclarationNode.SemicolonToken.IsMissing; private static bool ShouldAddBraceForAccessorDeclaration(AccessorDeclarationSyntax accessorDeclarationNode) { if (accessorDeclarationNode.Body == null && accessorDeclarationNode.ExpressionBody == null && accessorDeclarationNode.SemicolonToken.IsMissing) { // If the accessor doesn't have body, expression body and semicolon, let's check this case // for both event and property, // e.g. // int Bar // { // get; // se$$t // } // because if the getter doesn't have a body then setter also shouldn't have any body. // Don't check for indexer because the accessor for indexer should have body. var parent = accessorDeclarationNode.Parent; var parentOfParent = parent?.Parent; if (parent is AccessorListSyntax accessorListNode && parentOfParent is PropertyDeclarationSyntax) { var otherAccessors = accessorListNode.Accessors .Except(new[] { accessorDeclarationNode }) .ToImmutableArray(); if (!otherAccessors.IsEmpty) { return !otherAccessors.Any( accessor => accessor.Body == null && accessor.ExpressionBody == null && !accessor.SemicolonToken.IsMissing); } } return true; } return false; } /// <summary> /// For indexer, switch, try and catch syntax node without braces, if it is the last child of its parent, it would /// use its parent's close brace as its own. /// Example: /// class Bar /// { /// int th$$is[int i] /// } /// In this case, parser would think the last '}' belongs to the indexer, not the class. /// Therefore, only check if the open brace is missing for these 4 types of SyntaxNode /// </summary> private static bool ShouldAddBraceForIndexerDeclaration(IndexerDeclarationSyntax indexerDeclarationNode, int caretPosition) { if (WithinAttributeLists(indexerDeclarationNode, caretPosition) || WithinBraces(indexerDeclarationNode.AccessorList, caretPosition)) { return false; } // Make sure it has brackets var (openBracket, closeBracket) = indexerDeclarationNode.ParameterList.GetBrackets(); if (openBracket.IsMissing || closeBracket.IsMissing) { return false; } // If both accessorList and body is empty if ((indexerDeclarationNode.AccessorList == null || indexerDeclarationNode.AccessorList.IsMissing) && indexerDeclarationNode.ExpressionBody == null) { return true; } return indexerDeclarationNode.AccessorList != null && indexerDeclarationNode.AccessorList.OpenBraceToken.IsMissing; } // For the Switch, Try, Catch, Finally node // e.g. // class Bar // { // void Main() // { // tr$$y // } // } // In this case, the last close brace of 'void Main()' would be thought as a part of the try statement, // and the last close brace of 'Bar' would be thought as a part of Main() // So for these case, , just check if the open brace is missing. private static bool ShouldAddBraceForSwitchStatement(SwitchStatementSyntax switchStatementNode) => !switchStatementNode.OpenParenToken.IsMissing && !switchStatementNode.CloseParenToken.IsMissing && switchStatementNode.OpenBraceToken.IsMissing; private static bool ShouldAddBraceForTryStatement(TryStatementSyntax tryStatementNode, int caretPosition) => !tryStatementNode.TryKeyword.IsMissing && tryStatementNode.Block.OpenBraceToken.IsMissing && !tryStatementNode.Block.Span.Contains(caretPosition); private static bool ShouldAddBraceForCatchClause(CatchClauseSyntax catchClauseSyntax, int caretPosition) => !catchClauseSyntax.CatchKeyword.IsMissing && catchClauseSyntax.Block.OpenBraceToken.IsMissing && !catchClauseSyntax.Block.Span.Contains(caretPosition); private static bool ShouldAddBraceForFinallyClause(FinallyClauseSyntax finallyClauseNode, int caretPosition) => !finallyClauseNode.FinallyKeyword.IsMissing && finallyClauseNode.Block.OpenBraceToken.IsMissing && !finallyClauseNode.Block.Span.Contains(caretPosition); // For all the embeddedStatementOwners, // if the embeddedStatement is not block, insert the the braces if its statement is not block. private static bool ShouldAddBraceForDoStatement(DoStatementSyntax doStatementNode, int caretPosition) => !doStatementNode.DoKeyword.IsMissing && doStatementNode.Statement is not BlockSyntax && doStatementNode.DoKeyword.FullSpan.Contains(caretPosition); private static bool ShouldAddBraceForCommonForEachStatement(CommonForEachStatementSyntax commonForEachStatementNode, int caretPosition) => commonForEachStatementNode.Statement is not BlockSyntax && !commonForEachStatementNode.OpenParenToken.IsMissing && !commonForEachStatementNode.CloseParenToken.IsMissing && !WithinEmbeddedStatement(commonForEachStatementNode, caretPosition); private static bool ShouldAddBraceForForStatement(ForStatementSyntax forStatementNode, int caretPosition) => forStatementNode.Statement is not BlockSyntax && !forStatementNode.OpenParenToken.IsMissing && !forStatementNode.CloseParenToken.IsMissing && !WithinEmbeddedStatement(forStatementNode, caretPosition); private static bool ShouldAddBraceForIfStatement(IfStatementSyntax ifStatementNode, int caretPosition) => ifStatementNode.Statement is not BlockSyntax && !ifStatementNode.OpenParenToken.IsMissing && !ifStatementNode.CloseParenToken.IsMissing && !WithinEmbeddedStatement(ifStatementNode, caretPosition); private static bool ShouldAddBraceForElseClause(ElseClauseSyntax elseClauseNode, int caretPosition) { // In case it is an else-if clause, if the statement is IfStatement, use its insertion statement // otherwise, use the end of the else keyword // Example: // Before: if (a) // { // } else i$$f (b) // After: if (a) // { // } else if (b) // { // $$ // } if (elseClauseNode.Statement is IfStatementSyntax ifStatementNode) { return ShouldAddBraceForIfStatement(ifStatementNode, caretPosition); } else { // Here it should be an elseClause // like: // if (a) // { // } els$$e { // } // So only check the its statement return elseClauseNode.Statement is not BlockSyntax && !WithinEmbeddedStatement(elseClauseNode, caretPosition); } } private static bool ShouldAddBraceForLockStatement(LockStatementSyntax lockStatementNode, int caretPosition) => lockStatementNode.Statement is not BlockSyntax && !lockStatementNode.OpenParenToken.IsMissing && !lockStatementNode.CloseParenToken.IsMissing && !WithinEmbeddedStatement(lockStatementNode, caretPosition); private static bool ShouldAddBraceForUsingStatement(UsingStatementSyntax usingStatementNode, int caretPosition) => usingStatementNode.Statement is not BlockSyntax && !usingStatementNode.OpenParenToken.IsMissing && !usingStatementNode.CloseParenToken.IsMissing && !WithinEmbeddedStatement(usingStatementNode, caretPosition); private static bool ShouldAddBraceForWhileStatement(WhileStatementSyntax whileStatementNode, int caretPosition) => whileStatementNode.Statement is not BlockSyntax && !whileStatementNode.OpenParenToken.IsMissing && !whileStatementNode.CloseParenToken.IsMissing && !WithinEmbeddedStatement(whileStatementNode, caretPosition); private static bool WithinAttributeLists(SyntaxNode node, int caretPosition) { var attributeLists = node.GetAttributeLists(); return attributeLists.Span.Contains(caretPosition); } private static bool WithinBraces(SyntaxNode? node, int caretPosition) { var (openBrace, closeBrace) = node.GetBraces(); return TextSpan.FromBounds(openBrace.SpanStart, closeBrace.Span.End).Contains(caretPosition); } private static bool WithinMethodBody(SyntaxNode node, int caretPosition) { if (node is BaseMethodDeclarationSyntax { Body: { } baseMethodBody }) { return baseMethodBody.Span.Contains(caretPosition); } if (node is LocalFunctionStatementSyntax { Body: { } localFunctionBody }) { return localFunctionBody.Span.Contains(caretPosition); } return false; } private static bool HasNoBrace(SyntaxNode node) { var (openBrace, closeBrace) = node.GetBraces(); return openBrace.IsKind(SyntaxKind.None) && closeBrace.IsKind(SyntaxKind.None) || openBrace.IsMissing && closeBrace.IsMissing; } private static bool WithinEmbeddedStatement(SyntaxNode node, int caretPosition) => node.GetEmbeddedStatement()?.Span.Contains(caretPosition) ?? false; #endregion #region ShouldRemoveBraceCheck private static bool ShouldRemoveBraces(SyntaxNode node, int caretPosition) => node switch { ObjectCreationExpressionSyntax objectCreationExpressionNode => ShouldRemoveBraceForObjectCreationExpression(objectCreationExpressionNode), AccessorDeclarationSyntax accessorDeclarationNode => ShouldRemoveBraceForAccessorDeclaration(accessorDeclarationNode, caretPosition), PropertyDeclarationSyntax propertyDeclarationNode => ShouldRemoveBraceForPropertyDeclaration(propertyDeclarationNode, caretPosition), EventDeclarationSyntax eventDeclarationNode => ShouldRemoveBraceForEventDeclaration(eventDeclarationNode, caretPosition), _ => false, }; /// <summary> /// Remove the braces if the ObjectCreationExpression has an empty Initializer. /// </summary> private static bool ShouldRemoveBraceForObjectCreationExpression(ObjectCreationExpressionSyntax objectCreationExpressionNode) { var initializer = objectCreationExpressionNode.Initializer; return initializer != null && initializer.Expressions.IsEmpty(); } // Only do this when it is an accessor in property // Since it is illegal to have something like // int this[int i] { get; set;} // event EventHandler Bar {add; remove;} private static bool ShouldRemoveBraceForAccessorDeclaration(AccessorDeclarationSyntax accessorDeclarationNode, int caretPosition) => accessorDeclarationNode.Body != null && accessorDeclarationNode.Body.Statements.IsEmpty() && accessorDeclarationNode.ExpressionBody == null && accessorDeclarationNode.Parent != null && accessorDeclarationNode.Parent.IsParentKind(SyntaxKind.PropertyDeclaration) && accessorDeclarationNode.Body.Span.Contains(caretPosition); private static bool ShouldRemoveBraceForPropertyDeclaration(PropertyDeclarationSyntax propertyDeclarationNode, int caretPosition) { // If a property just has an empty accessorList, like // int i $${ } // then remove the braces and change it to a field // int i; if (propertyDeclarationNode.AccessorList != null && propertyDeclarationNode.ExpressionBody == null) { var accessorList = propertyDeclarationNode.AccessorList; return accessorList.Span.Contains(caretPosition) && accessorList.Accessors.IsEmpty(); } return false; } private static bool ShouldRemoveBraceForEventDeclaration(EventDeclarationSyntax eventDeclarationNode, int caretPosition) { // If an event declaration just has an empty accessorList, // like // event EventHandler e$$ { } // then change it to a event field declaration // event EventHandler e; var accessorList = eventDeclarationNode.AccessorList; return accessorList != null && accessorList.Span.Contains(caretPosition) && accessorList.Accessors.IsEmpty(); } #endregion #region AddBrace private static AccessorListSyntax GetAccessorListNode(IEditorOptions editorOptions) => SyntaxFactory.AccessorList().WithOpenBraceToken(GetOpenBrace(editorOptions)).WithCloseBraceToken(GetCloseBrace(editorOptions)); private static InitializerExpressionSyntax GetInitializerExpressionNode(IEditorOptions editorOptions) => SyntaxFactory.InitializerExpression(SyntaxKind.ObjectInitializerExpression) .WithOpenBraceToken(GetOpenBrace(editorOptions)); private static BlockSyntax GetBlockNode(IEditorOptions editorOptions) => SyntaxFactory.Block().WithOpenBraceToken(GetOpenBrace(editorOptions)).WithCloseBraceToken(GetCloseBrace(editorOptions)); private static SyntaxToken GetOpenBrace(IEditorOptions editorOptions) => SyntaxFactory.Token( leading: SyntaxTriviaList.Empty, kind: SyntaxKind.OpenBraceToken, trailing: SyntaxTriviaList.Create(GetNewLineTrivia(editorOptions))) .WithAdditionalAnnotations(s_openBracePositionAnnotation); private static SyntaxToken GetCloseBrace(IEditorOptions editorOptions) => SyntaxFactory.Token( leading: SyntaxTriviaList.Empty, kind: SyntaxKind.CloseBraceToken, trailing: SyntaxTriviaList.Create(GetNewLineTrivia(editorOptions))); private static SyntaxTrivia GetNewLineTrivia(IEditorOptions editorOptions) { var newLineString = editorOptions.GetNewLineCharacter(); return SyntaxFactory.EndOfLine(newLineString); } /// <summary> /// Add braces to the <param name="node"/>. /// For FieldDeclaration and EventFieldDeclaration, it will change them to PropertyDeclaration and EventDeclaration /// </summary> private static SyntaxNode WithBraces(SyntaxNode node, IEditorOptions editorOptions) => node switch { BaseTypeDeclarationSyntax baseTypeDeclarationNode => WithBracesForBaseTypeDeclaration(baseTypeDeclarationNode, editorOptions), ObjectCreationExpressionSyntax objectCreationExpressionNode => GetObjectCreationExpressionWithInitializer(objectCreationExpressionNode, editorOptions), FieldDeclarationSyntax fieldDeclarationNode when fieldDeclarationNode.Declaration.Variables.IsSingle() => ConvertFieldDeclarationToPropertyDeclaration(fieldDeclarationNode, editorOptions), EventFieldDeclarationSyntax eventFieldDeclarationNode => ConvertEventFieldDeclarationToEventDeclaration(eventFieldDeclarationNode, editorOptions), BaseMethodDeclarationSyntax baseMethodDeclarationNode => AddBlockToBaseMethodDeclaration(baseMethodDeclarationNode, editorOptions), LocalFunctionStatementSyntax localFunctionStatementNode => AddBlockToLocalFunctionDeclaration(localFunctionStatementNode, editorOptions), AccessorDeclarationSyntax accessorDeclarationNode => AddBlockToAccessorDeclaration(accessorDeclarationNode, editorOptions), _ when node.IsEmbeddedStatementOwner() => AddBlockToEmbeddedStatementOwner(node, editorOptions), _ => throw ExceptionUtilities.UnexpectedValue(node), }; /// <summary> /// Add braces to <param name="baseTypeDeclarationNode"/>. /// </summary> private static BaseTypeDeclarationSyntax WithBracesForBaseTypeDeclaration( BaseTypeDeclarationSyntax baseTypeDeclarationNode, IEditorOptions editorOptions) => baseTypeDeclarationNode.WithOpenBraceToken(GetOpenBrace(editorOptions)) .WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken)); /// <summary> /// Add an empty initializer to <param name="objectCreationExpressionNode"/>. /// </summary> private static ObjectCreationExpressionSyntax GetObjectCreationExpressionWithInitializer( ObjectCreationExpressionSyntax objectCreationExpressionNode, IEditorOptions editorOptions) => objectCreationExpressionNode.WithInitializer(GetInitializerExpressionNode(editorOptions)); /// <summary> /// Convert <param name="fieldDeclarationNode"/> to a property declarations. /// </summary> private static PropertyDeclarationSyntax ConvertFieldDeclarationToPropertyDeclaration( FieldDeclarationSyntax fieldDeclarationNode, IEditorOptions editorOptions) => SyntaxFactory.PropertyDeclaration( fieldDeclarationNode.AttributeLists, fieldDeclarationNode.Modifiers, fieldDeclarationNode.Declaration.Type, explicitInterfaceSpecifier: null, identifier: fieldDeclarationNode.Declaration.Variables[0].Identifier, accessorList: GetAccessorListNode(editorOptions), expressionBody: null, initializer: null, semicolonToken: SyntaxFactory.Token(SyntaxKind.None)).WithTriviaFrom(fieldDeclarationNode); /// <summary> /// Convert <param name="eventFieldDeclarationNode"/> to an eventDeclaration node. /// </summary> private static EventDeclarationSyntax ConvertEventFieldDeclarationToEventDeclaration( EventFieldDeclarationSyntax eventFieldDeclarationNode, IEditorOptions editorOptions) => SyntaxFactory.EventDeclaration( eventFieldDeclarationNode.AttributeLists, eventFieldDeclarationNode.Modifiers, eventFieldDeclarationNode.EventKeyword, eventFieldDeclarationNode.Declaration.Type, explicitInterfaceSpecifier: null, identifier: eventFieldDeclarationNode.Declaration.Variables[0].Identifier, accessorList: GetAccessorListNode(editorOptions), semicolonToken: SyntaxFactory.Token(SyntaxKind.None)).WithTriviaFrom(eventFieldDeclarationNode); /// <summary> /// Add an empty block to <param name="baseMethodDeclarationNode"/>. /// </summary> private static BaseMethodDeclarationSyntax AddBlockToBaseMethodDeclaration( BaseMethodDeclarationSyntax baseMethodDeclarationNode, IEditorOptions editorOptions) => baseMethodDeclarationNode.WithBody(GetBlockNode(editorOptions)) // When the method declaration with no body is parsed, it has an invisible trailing semicolon. Make sure it is removed. .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); /// <summary> /// Add an empty block to <param name="localFunctionStatementNode"/>. /// </summary> private static LocalFunctionStatementSyntax AddBlockToLocalFunctionDeclaration( LocalFunctionStatementSyntax localFunctionStatementNode, IEditorOptions editorOptions) => localFunctionStatementNode.WithBody(GetBlockNode(editorOptions)) // When the local method declaration with no body is parsed, it has an invisible trailing semicolon. Make sure it is removed. .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); /// <summary> /// Add an empty block to <param name="accessorDeclarationNode"/>. /// </summary> private static AccessorDeclarationSyntax AddBlockToAccessorDeclaration( AccessorDeclarationSyntax accessorDeclarationNode, IEditorOptions editorOptions) => accessorDeclarationNode.WithBody(GetBlockNode(editorOptions)) // When the accessor with no body is parsed, it has an invisible trailing semicolon. Make sure it is removed. .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); /// <summary> /// Add a block with <param name="extraNodeInsertedBetweenBraces"/> to <param name="embeddedStatementOwner"/> /// </summary> private static SyntaxNode AddBlockToEmbeddedStatementOwner( SyntaxNode embeddedStatementOwner, IEditorOptions editorOptions, StatementSyntax? extraNodeInsertedBetweenBraces = null) { var block = extraNodeInsertedBetweenBraces != null ? GetBlockNode(editorOptions).WithStatements(new SyntaxList<StatementSyntax>(extraNodeInsertedBetweenBraces)) : GetBlockNode(editorOptions); return embeddedStatementOwner switch { DoStatementSyntax doStatementNode => doStatementNode.WithStatement(block), ForEachStatementSyntax forEachStatementNode => forEachStatementNode.WithStatement(block), ForStatementSyntax forStatementNode => forStatementNode.WithStatement(block), IfStatementSyntax ifStatementNode => ifStatementNode.WithStatement(block), ElseClauseSyntax elseClauseNode => elseClauseNode.WithStatement(block), WhileStatementSyntax whileStatementNode => whileStatementNode.WithStatement(block), UsingStatementSyntax usingStatementNode => usingStatementNode.WithStatement(block), LockStatementSyntax lockStatementNode => lockStatementNode.WithStatement(block), _ => throw ExceptionUtilities.UnexpectedValue(embeddedStatementOwner) }; } #endregion #region RemoveBrace /// <summary> /// Remove the brace for the input syntax node /// For ObjectCreationExpressionSyntax, it would remove the initializer /// For PropertyDeclarationSyntax, it would change it to a FieldDeclaration /// For EventDeclarationSyntax, it would change it to eventFieldDeclaration /// For Accessor, it would change it to the empty version ending with semicolon. /// e.g get {} => get; /// </summary> private static SyntaxNode WithoutBraces(SyntaxNode node) => node switch { ObjectCreationExpressionSyntax objectCreationExpressionNode => RemoveInitializerForObjectCreationExpression(objectCreationExpressionNode), PropertyDeclarationSyntax propertyDeclarationNode => ConvertPropertyDeclarationToFieldDeclaration(propertyDeclarationNode), EventDeclarationSyntax eventDeclarationNode => ConvertEventDeclarationToEventFieldDeclaration(eventDeclarationNode), AccessorDeclarationSyntax accessorDeclarationNode => RemoveBodyForAccessorDeclarationNode(accessorDeclarationNode), _ => throw ExceptionUtilities.UnexpectedValue(node), }; /// <summary> /// Remove the initializer for <param name="objectCreationExpressionNode"/>. /// </summary> private static ObjectCreationExpressionSyntax RemoveInitializerForObjectCreationExpression( ObjectCreationExpressionSyntax objectCreationExpressionNode) { var objectCreationNodeWithoutInitializer = objectCreationExpressionNode.WithInitializer(null); // Filter the non-comments trivia // e.g. // Bar(new Foo() // I am some comments // { // $$ // }); // => // Bar(new Foo() // I am some comments); // In this case, 'I am somme comments' has an end of line triva, if not removed, it would make // the final result becomes // Bar(new Foo() // I am some comments // ); var trivia = objectCreationNodeWithoutInitializer.GetTrailingTrivia().Where(trivia => trivia.IsSingleOrMultiLineComment()); return objectCreationNodeWithoutInitializer.WithTrailingTrivia(trivia); } /// <summary> /// Convert <param name="propertyDeclarationNode"/> to fieldDeclaration. /// </summary> private static FieldDeclarationSyntax ConvertPropertyDeclarationToFieldDeclaration( PropertyDeclarationSyntax propertyDeclarationNode) => SyntaxFactory.FieldDeclaration( propertyDeclarationNode.AttributeLists, propertyDeclarationNode.Modifiers, SyntaxFactory.VariableDeclaration( propertyDeclarationNode.Type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator(propertyDeclarationNode.Identifier))), SyntaxFactory.Token(SyntaxKind.SemicolonToken)); /// <summary> /// Convert <param name="eventDeclarationNode"/> to EventFieldDeclaration. /// </summary> private static EventFieldDeclarationSyntax ConvertEventDeclarationToEventFieldDeclaration( EventDeclarationSyntax eventDeclarationNode) => SyntaxFactory.EventFieldDeclaration( eventDeclarationNode.AttributeLists, eventDeclarationNode.Modifiers, SyntaxFactory.VariableDeclaration( eventDeclarationNode.Type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator(eventDeclarationNode.Identifier)))); /// <summary> /// Remove the body of <param name="accessorDeclarationNode"/>. /// </summary> private static AccessorDeclarationSyntax RemoveBodyForAccessorDeclarationNode(AccessorDeclarationSyntax accessorDeclarationNode) => accessorDeclarationNode .WithBody(null).WithoutTrailingTrivia().WithSemicolonToken( SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.SemicolonToken, SyntaxTriviaList.Empty)); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion { internal partial class AutomaticLineEnderCommandHandler { #region NodeReplacementHelpers private static (SyntaxNode newRoot, int nextCaretPosition) ReplaceStatementOwnerAndInsertStatement( Document document, SyntaxNode root, SyntaxNode oldNode, SyntaxNode newNode, SyntaxNode anchorNode, ImmutableArray<StatementSyntax> nodesToInsert, CancellationToken cancellationToken) { var rootEditor = new SyntaxEditor(root, document.Project.Solution.Workspace); // 1. Insert the node before anchor node rootEditor.InsertAfter(anchorNode, nodesToInsert); // 2. Replace the old node with newNode. (new node is the node with correct braces) rootEditor.ReplaceNode(oldNode, newNode.WithAdditionalAnnotations(s_replacementNodeAnnotation)); var newRoot = rootEditor.GetChangedRoot(); // 4. Format the new node so that the inserted braces/blocks would have correct indentation and formatting. var newNodeAfterInsertion = newRoot.GetAnnotatedNodes(s_replacementNodeAnnotation).Single(); var formattedNewRoot = Formatter.Format( newRoot, newNodeAfterInsertion.Span, document.Project.Solution.Workspace, cancellationToken: cancellationToken); // 4. Use the annotation to find the end of the open brace, it would be the new caret position var nextCaretPosition = formattedNewRoot.GetAnnotatedTokens(s_openBracePositionAnnotation).Single().Span.End; return (formattedNewRoot, nextCaretPosition); } private static SyntaxNode ReplaceNodeAndFormat( Document document, SyntaxNode root, SyntaxNode oldNode, SyntaxNode newNode, CancellationToken cancellationToken) { // 1. Tag the new node so that it could be found later. var annotatedNewNode = newNode.WithAdditionalAnnotations(s_replacementNodeAnnotation); // 2. Replace the old node with newNode. (new node is the node with correct braces) var newRoot = root.ReplaceNode( oldNode, annotatedNewNode); // 3. Find the newNode in the new syntax root. var newNodeAfterInsertion = newRoot.GetAnnotatedNodes(s_replacementNodeAnnotation).Single(); // 4. Format the new node so that the inserted braces/blocks would have correct indentation and formatting. var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var formattedNewRoot = Formatter.Format( newRoot, newNodeAfterInsertion.Span, document.Project.Solution.Workspace, options, cancellationToken: cancellationToken); return formattedNewRoot; } #endregion #region EmbeddedStatementModificationHelpers private static (SyntaxNode newRoot, int nextCaretPosition) AddBraceToEmbeddedStatementOwner( Document document, SyntaxNode root, SyntaxNode embeddedStatementOwner, IEditorOptions editorOptions, CancellationToken cancellationToken) { // If there is no inner statement, just add an empty block to it. // e.g. // class Bar // { // if (true)$$ // } // => // class Bar // { // if (true) // { // } // } var statement = embeddedStatementOwner.GetEmbeddedStatement(); if (statement == null || statement.IsMissing) { var newRoot = ReplaceNodeAndFormat( document, root, embeddedStatementOwner, WithBraces(embeddedStatementOwner, editorOptions), cancellationToken); // Locate the open brace token, and move the caret after it. var nextCaretPosition = GetOpenBraceSpanEnd(newRoot); return (newRoot, nextCaretPosition); } // There is an inner statement, it needs to be handled differently in addition to adding the block, // For while, ForEach, Lock and Using statement, // If there is an statement in the embeddedStatementOwner, // move the old statement next to the statementOwner, // and insert a empty block into the statementOwner, // e.g. // before: // whi$$le(true) // var i = 1; // for this case 'var i = 1;' is thought as the inner statement, // // after: // while(true) // { // $$ // } // var i = 1; return embeddedStatementOwner switch { WhileStatementSyntax or ForEachStatementSyntax or ForStatementSyntax or LockStatementSyntax or UsingStatementSyntax => ReplaceStatementOwnerAndInsertStatement( document, root, oldNode: embeddedStatementOwner, newNode: AddBlockToEmbeddedStatementOwner(embeddedStatementOwner, editorOptions), anchorNode: embeddedStatementOwner, nodesToInsert: ImmutableArray<StatementSyntax>.Empty.Add(statement), cancellationToken), DoStatementSyntax doStatementNode => AddBraceToDoStatement(document, root, doStatementNode, editorOptions, statement, cancellationToken), IfStatementSyntax ifStatementNode => AddBraceToIfStatement(document, root, ifStatementNode, editorOptions, statement, cancellationToken), ElseClauseSyntax elseClauseNode => AddBraceToElseClause(document, root, elseClauseNode, editorOptions, statement, cancellationToken), _ => throw ExceptionUtilities.UnexpectedValue(embeddedStatementOwner), }; } private static (SyntaxNode newRoot, int nextCaretPosition) AddBraceToDoStatement( Document document, SyntaxNode root, DoStatementSyntax doStatementNode, IEditorOptions editorOptions, StatementSyntax innerStatement, CancellationToken cancellationToken) { // If this do statement doesn't end with the 'while' parts // e.g: // before: // d$$o // Print("hello"); // after: // do // { // $$ // } // Print("hello"); if (doStatementNode.WhileKeyword.IsMissing && doStatementNode.SemicolonToken.IsMissing && doStatementNode.OpenParenToken.IsMissing && doStatementNode.CloseParenToken.IsMissing) { return ReplaceStatementOwnerAndInsertStatement( document, root, oldNode: doStatementNode, newNode: AddBlockToEmbeddedStatementOwner(doStatementNode, editorOptions), anchorNode: doStatementNode, nodesToInsert: ImmutableArray<StatementSyntax>.Empty.Add(innerStatement), cancellationToken); } // if the do statement has 'while' as an end // e.g: // before: // d$$o // Print("hello"); // while (true); // after: // do // { // $$ // Print("hello"); // } while(true); var newRoot = ReplaceNodeAndFormat( document, root, doStatementNode, AddBlockToEmbeddedStatementOwner(doStatementNode, editorOptions, innerStatement), cancellationToken); var nextCaretPosition = GetOpenBraceSpanEnd(newRoot); return (newRoot, nextCaretPosition); } private static (SyntaxNode newRoot, int nextCaretPosition) AddBraceToIfStatement( Document document, SyntaxNode root, IfStatementSyntax ifStatementNode, IEditorOptions editorOptions, StatementSyntax innerStatement, CancellationToken cancellationToken) { // This ifStatement doesn't have an else clause, and its parent is a Block. // Insert the innerStatement next to the ifStatement // e.g. // if ($$a) // Print(); // => // if (a) // { // $$ // } // Print(); if (ifStatementNode.Else == null && ifStatementNode.Parent is BlockSyntax) { return ReplaceStatementOwnerAndInsertStatement(document, root, ifStatementNode, AddBlockToEmbeddedStatementOwner(ifStatementNode, editorOptions), ifStatementNode, ImmutableArray<StatementSyntax>.Empty.Add(innerStatement), cancellationToken); } // If this IfStatement has an else statement after // e.g. // before: // if $$(true) // print("Hello"); // else {} // after: // if (true) // { // $$ // print("Hello"); // } // else {} var newRoot = ReplaceNodeAndFormat( document, root, ifStatementNode, AddBlockToEmbeddedStatementOwner(ifStatementNode, editorOptions, innerStatement), cancellationToken); var nextCaretPosition = GetOpenBraceSpanEnd(newRoot); return (newRoot, nextCaretPosition); } private static (SyntaxNode newRoot, int nextCaretPosition) AddBraceToElseClause( Document document, SyntaxNode root, ElseClauseSyntax elseClauseNode, IEditorOptions editorOptions, StatementSyntax innerStatement, CancellationToken cancellationToken) { // If this is an 'els$$e if(true)' statement, // then treat it as the selected node is the nested if statement if (elseClauseNode.Statement is IfStatementSyntax) { return AddBraceToEmbeddedStatementOwner(document, root, elseClauseNode.Statement, editorOptions, cancellationToken); } // Otherwise, it is just an ending else clause. // if its parent is an ifStatement and the parent of ifStatement is a block, insert the innerStatement after the ifStatement // e.g. before: // if (true) // { // } els$$e // Print(); // after: // if (true) // { // } els$$e // { // $$ // } // Print(); if (elseClauseNode.Parent is IfStatementSyntax { Parent: BlockSyntax }) { return ReplaceStatementOwnerAndInsertStatement(document, root, elseClauseNode, WithBraces(elseClauseNode, editorOptions), elseClauseNode.Parent!, ImmutableArray<StatementSyntax>.Empty.Add(innerStatement), cancellationToken); } // For all the other cases, // Put the innerStatement into the block // e.g. // if (a) // if (true) // { // } // else // { // $$ // Print(); // } // => // if (a) // if (true) // { // } // els$$e // Print(); var formattedNewRoot = ReplaceNodeAndFormat( document, root, elseClauseNode, AddBlockToEmbeddedStatementOwner(elseClauseNode, editorOptions, innerStatement), cancellationToken); var nextCaretPosition = formattedNewRoot.GetAnnotatedTokens(s_openBracePositionAnnotation).Single().Span.End; return (formattedNewRoot, nextCaretPosition); } #endregion #region ObjectCreationExpressionModificationHelpers private static (SyntaxNode newNode, SyntaxNode oldNode) ModifyObjectCreationExpressionNode( ObjectCreationExpressionSyntax objectCreationExpressionNode, bool addOrRemoveInitializer, IEditorOptions editorOptions) { // 1. Add '()' after the type. // e.g. var c = new Bar => var c = new Bar() var objectCreationNodeWithArgumentList = WithArgumentListIfNeeded(objectCreationExpressionNode); // 2. Add or remove initializer // e.g. var c = new Bar() => var c = new Bar() { } var objectCreationNodeWithCorrectInitializer = addOrRemoveInitializer ? WithBraces(objectCreationNodeWithArgumentList, editorOptions) : WithoutBraces(objectCreationNodeWithArgumentList); // 3. Handler the semicolon. // If the next token is a semicolon, e.g. // var l = new Ba$$r() { } => var l = new Ba$$r() { }; var nextToken = objectCreationExpressionNode.GetLastToken(includeZeroWidth: true).GetNextToken(includeZeroWidth: true); if (nextToken.IsKind(SyntaxKind.SemicolonToken) && nextToken.Parent != null && nextToken.Parent.Contains(objectCreationExpressionNode)) { var objectCreationNodeContainer = nextToken.Parent; // Replace the old object creation node and add the semicolon token. // Note: need to move the trailing trivia of the objectCreationExpressionNode after the semicolon token // e.g. // var l = new Bar() {} // I am some comments // => // var l = new Bar() {}; // I am some comments var replacementContainerNode = objectCreationNodeContainer.ReplaceSyntax( nodes: SpecializedCollections.SingletonCollection(objectCreationExpressionNode), (_, _) => objectCreationNodeWithCorrectInitializer.WithoutTrailingTrivia(), tokens: SpecializedCollections.SingletonCollection(nextToken), computeReplacementToken: (_, _) => SyntaxFactory.Token(SyntaxKind.SemicolonToken).WithTrailingTrivia(objectCreationNodeWithCorrectInitializer.GetTrailingTrivia()), trivia: Enumerable.Empty<SyntaxTrivia>(), computeReplacementTrivia: (_, syntaxTrivia) => syntaxTrivia); return (replacementContainerNode, objectCreationNodeContainer); } else { // No need to change the semicolon, just return the objectCreationExpression with correct initializer return (objectCreationNodeWithCorrectInitializer, objectCreationExpressionNode); } } /// <summary> /// Add argument list to the objectCreationExpression if needed. /// e.g. new Bar; => new Bar(); /// </summary> private static ObjectCreationExpressionSyntax WithArgumentListIfNeeded(ObjectCreationExpressionSyntax objectCreationExpressionNode) { var argumentList = objectCreationExpressionNode.ArgumentList; var hasArgumentList = argumentList != null && !argumentList.IsMissing; if (!hasArgumentList) { // Make sure the trailing trivia is passed to the argument list // like var l = new List\r\n => // var l = new List()\r\r var typeNode = objectCreationExpressionNode.Type; var newArgumentList = SyntaxFactory.ArgumentList().WithTrailingTrivia(typeNode.GetTrailingTrivia()); var newTypeNode = typeNode.WithoutTrivia(); return objectCreationExpressionNode.WithType(newTypeNode).WithArgumentList(newArgumentList); } return objectCreationExpressionNode; } #endregion #region ShouldAddBraceCheck private static bool ShouldAddBraces(SyntaxNode node, int caretPosition) => node switch { NamespaceDeclarationSyntax namespaceDeclarationNode => ShouldAddBraceForNamespaceDeclaration(namespaceDeclarationNode, caretPosition), BaseTypeDeclarationSyntax baseTypeDeclarationNode => ShouldAddBraceForBaseTypeDeclaration(baseTypeDeclarationNode, caretPosition), BaseMethodDeclarationSyntax baseMethodDeclarationNode => ShouldAddBraceForBaseMethodDeclaration(baseMethodDeclarationNode, caretPosition), LocalFunctionStatementSyntax localFunctionStatementNode => ShouldAddBraceForLocalFunctionStatement(localFunctionStatementNode, caretPosition), ObjectCreationExpressionSyntax objectCreationExpressionNode => ShouldAddBraceForObjectCreationExpression(objectCreationExpressionNode), BaseFieldDeclarationSyntax baseFieldDeclarationNode => ShouldAddBraceForBaseFieldDeclaration(baseFieldDeclarationNode), AccessorDeclarationSyntax accessorDeclarationNode => ShouldAddBraceForAccessorDeclaration(accessorDeclarationNode), IndexerDeclarationSyntax indexerDeclarationNode => ShouldAddBraceForIndexerDeclaration(indexerDeclarationNode, caretPosition), SwitchStatementSyntax switchStatementNode => ShouldAddBraceForSwitchStatement(switchStatementNode), TryStatementSyntax tryStatementNode => ShouldAddBraceForTryStatement(tryStatementNode, caretPosition), CatchClauseSyntax catchClauseNode => ShouldAddBraceForCatchClause(catchClauseNode, caretPosition), FinallyClauseSyntax finallyClauseNode => ShouldAddBraceForFinallyClause(finallyClauseNode, caretPosition), DoStatementSyntax doStatementNode => ShouldAddBraceForDoStatement(doStatementNode, caretPosition), CommonForEachStatementSyntax commonForEachStatementNode => ShouldAddBraceForCommonForEachStatement(commonForEachStatementNode, caretPosition), ForStatementSyntax forStatementNode => ShouldAddBraceForForStatement(forStatementNode, caretPosition), IfStatementSyntax ifStatementNode => ShouldAddBraceForIfStatement(ifStatementNode, caretPosition), ElseClauseSyntax elseClauseNode => ShouldAddBraceForElseClause(elseClauseNode, caretPosition), LockStatementSyntax lockStatementNode => ShouldAddBraceForLockStatement(lockStatementNode, caretPosition), UsingStatementSyntax usingStatementNode => ShouldAddBraceForUsingStatement(usingStatementNode, caretPosition), WhileStatementSyntax whileStatementNode => ShouldAddBraceForWhileStatement(whileStatementNode, caretPosition), _ => false, }; /// <summary> /// For namespace, make sure it has name there is no braces /// </summary> private static bool ShouldAddBraceForNamespaceDeclaration(NamespaceDeclarationSyntax namespaceDeclarationNode, int caretPosition) => !namespaceDeclarationNode.Name.IsMissing && HasNoBrace(namespaceDeclarationNode) && !WithinAttributeLists(namespaceDeclarationNode, caretPosition) && !WithinBraces(namespaceDeclarationNode, caretPosition); /// <summary> /// For class/struct/enum ..., make sure it has name and there is no braces. /// </summary> private static bool ShouldAddBraceForBaseTypeDeclaration(BaseTypeDeclarationSyntax baseTypeDeclarationNode, int caretPosition) => !baseTypeDeclarationNode.Identifier.IsMissing && HasNoBrace(baseTypeDeclarationNode) && !WithinAttributeLists(baseTypeDeclarationNode, caretPosition) && !WithinBraces(baseTypeDeclarationNode, caretPosition); /// <summary> /// For method, make sure it has a ParameterList, because later braces would be inserted after the Parameterlist /// </summary> private static bool ShouldAddBraceForBaseMethodDeclaration(BaseMethodDeclarationSyntax baseMethodDeclarationNode, int caretPosition) => baseMethodDeclarationNode.ExpressionBody == null && baseMethodDeclarationNode.Body == null && !baseMethodDeclarationNode.ParameterList.IsMissing && baseMethodDeclarationNode.SemicolonToken.IsMissing && !WithinAttributeLists(baseMethodDeclarationNode, caretPosition) && !WithinMethodBody(baseMethodDeclarationNode, caretPosition) // Make sure we don't insert braces for method in Interface. && !baseMethodDeclarationNode.IsParentKind(SyntaxKind.InterfaceDeclaration); /// <summary> /// For local Function, make sure it has a ParameterList, because later braces would be inserted after the Parameterlist /// </summary> private static bool ShouldAddBraceForLocalFunctionStatement(LocalFunctionStatementSyntax localFunctionStatementNode, int caretPosition) => localFunctionStatementNode.ExpressionBody == null && localFunctionStatementNode.Body == null && !localFunctionStatementNode.ParameterList.IsMissing && !WithinAttributeLists(localFunctionStatementNode, caretPosition) && !WithinMethodBody(localFunctionStatementNode, caretPosition); /// <summary> /// Add brace for ObjectCreationExpression if it doesn't have initializer /// </summary> private static bool ShouldAddBraceForObjectCreationExpression(ObjectCreationExpressionSyntax objectCreationExpressionNode) => objectCreationExpressionNode.Initializer == null; /// <summary> /// Add braces for field and event field if they only have one variable, semicolon is missing and don't have readonly keyword /// Example: /// public int Bar$$ => /// public int Bar /// { /// $$ /// } /// This would change field to property, and change event field to event declaration. /// </summary> private static bool ShouldAddBraceForBaseFieldDeclaration(BaseFieldDeclarationSyntax baseFieldDeclarationNode) => baseFieldDeclarationNode.Declaration.Variables.Count == 1 && baseFieldDeclarationNode.Declaration.Variables[0].Initializer == null && !baseFieldDeclarationNode.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) && baseFieldDeclarationNode.SemicolonToken.IsMissing; private static bool ShouldAddBraceForAccessorDeclaration(AccessorDeclarationSyntax accessorDeclarationNode) { if (accessorDeclarationNode.Body == null && accessorDeclarationNode.ExpressionBody == null && accessorDeclarationNode.SemicolonToken.IsMissing) { // If the accessor doesn't have body, expression body and semicolon, let's check this case // for both event and property, // e.g. // int Bar // { // get; // se$$t // } // because if the getter doesn't have a body then setter also shouldn't have any body. // Don't check for indexer because the accessor for indexer should have body. var parent = accessorDeclarationNode.Parent; var parentOfParent = parent?.Parent; if (parent is AccessorListSyntax accessorListNode && parentOfParent is PropertyDeclarationSyntax) { var otherAccessors = accessorListNode.Accessors .Except(new[] { accessorDeclarationNode }) .ToImmutableArray(); if (!otherAccessors.IsEmpty) { return !otherAccessors.Any( accessor => accessor.Body == null && accessor.ExpressionBody == null && !accessor.SemicolonToken.IsMissing); } } return true; } return false; } /// <summary> /// For indexer, switch, try and catch syntax node without braces, if it is the last child of its parent, it would /// use its parent's close brace as its own. /// Example: /// class Bar /// { /// int th$$is[int i] /// } /// In this case, parser would think the last '}' belongs to the indexer, not the class. /// Therefore, only check if the open brace is missing for these 4 types of SyntaxNode /// </summary> private static bool ShouldAddBraceForIndexerDeclaration(IndexerDeclarationSyntax indexerDeclarationNode, int caretPosition) { if (WithinAttributeLists(indexerDeclarationNode, caretPosition) || WithinBraces(indexerDeclarationNode.AccessorList, caretPosition)) { return false; } // Make sure it has brackets var (openBracket, closeBracket) = indexerDeclarationNode.ParameterList.GetBrackets(); if (openBracket.IsMissing || closeBracket.IsMissing) { return false; } // If both accessorList and body is empty if ((indexerDeclarationNode.AccessorList == null || indexerDeclarationNode.AccessorList.IsMissing) && indexerDeclarationNode.ExpressionBody == null) { return true; } return indexerDeclarationNode.AccessorList != null && indexerDeclarationNode.AccessorList.OpenBraceToken.IsMissing; } // For the Switch, Try, Catch, Finally node // e.g. // class Bar // { // void Main() // { // tr$$y // } // } // In this case, the last close brace of 'void Main()' would be thought as a part of the try statement, // and the last close brace of 'Bar' would be thought as a part of Main() // So for these case, just check if the open brace is missing. private static bool ShouldAddBraceForSwitchStatement(SwitchStatementSyntax switchStatementNode) => !switchStatementNode.SwitchKeyword.IsMissing && switchStatementNode.OpenBraceToken.IsMissing; private static bool ShouldAddBraceForTryStatement(TryStatementSyntax tryStatementNode, int caretPosition) => !tryStatementNode.TryKeyword.IsMissing && tryStatementNode.Block.OpenBraceToken.IsMissing && !tryStatementNode.Block.Span.Contains(caretPosition); private static bool ShouldAddBraceForCatchClause(CatchClauseSyntax catchClauseSyntax, int caretPosition) => !catchClauseSyntax.CatchKeyword.IsMissing && catchClauseSyntax.Block.OpenBraceToken.IsMissing && !catchClauseSyntax.Block.Span.Contains(caretPosition); private static bool ShouldAddBraceForFinallyClause(FinallyClauseSyntax finallyClauseNode, int caretPosition) => !finallyClauseNode.FinallyKeyword.IsMissing && finallyClauseNode.Block.OpenBraceToken.IsMissing && !finallyClauseNode.Block.Span.Contains(caretPosition); // For all the embeddedStatementOwners, // if the embeddedStatement is not block, insert the the braces if its statement is not block. private static bool ShouldAddBraceForDoStatement(DoStatementSyntax doStatementNode, int caretPosition) => !doStatementNode.DoKeyword.IsMissing && doStatementNode.Statement is not BlockSyntax && doStatementNode.DoKeyword.FullSpan.Contains(caretPosition); private static bool ShouldAddBraceForCommonForEachStatement(CommonForEachStatementSyntax commonForEachStatementNode, int caretPosition) => commonForEachStatementNode.Statement is not BlockSyntax && !commonForEachStatementNode.OpenParenToken.IsMissing && !commonForEachStatementNode.CloseParenToken.IsMissing && !WithinEmbeddedStatement(commonForEachStatementNode, caretPosition); private static bool ShouldAddBraceForForStatement(ForStatementSyntax forStatementNode, int caretPosition) => forStatementNode.Statement is not BlockSyntax && !forStatementNode.OpenParenToken.IsMissing && !forStatementNode.CloseParenToken.IsMissing && !WithinEmbeddedStatement(forStatementNode, caretPosition); private static bool ShouldAddBraceForIfStatement(IfStatementSyntax ifStatementNode, int caretPosition) => ifStatementNode.Statement is not BlockSyntax && !ifStatementNode.OpenParenToken.IsMissing && !ifStatementNode.CloseParenToken.IsMissing && !WithinEmbeddedStatement(ifStatementNode, caretPosition); private static bool ShouldAddBraceForElseClause(ElseClauseSyntax elseClauseNode, int caretPosition) { // In case it is an else-if clause, if the statement is IfStatement, use its insertion statement // otherwise, use the end of the else keyword // Example: // Before: if (a) // { // } else i$$f (b) // After: if (a) // { // } else if (b) // { // $$ // } if (elseClauseNode.Statement is IfStatementSyntax ifStatementNode) { return ShouldAddBraceForIfStatement(ifStatementNode, caretPosition); } else { // Here it should be an elseClause // like: // if (a) // { // } els$$e { // } // So only check the its statement return elseClauseNode.Statement is not BlockSyntax && !WithinEmbeddedStatement(elseClauseNode, caretPosition); } } private static bool ShouldAddBraceForLockStatement(LockStatementSyntax lockStatementNode, int caretPosition) => lockStatementNode.Statement is not BlockSyntax && !lockStatementNode.OpenParenToken.IsMissing && !lockStatementNode.CloseParenToken.IsMissing && !WithinEmbeddedStatement(lockStatementNode, caretPosition); private static bool ShouldAddBraceForUsingStatement(UsingStatementSyntax usingStatementNode, int caretPosition) => usingStatementNode.Statement is not BlockSyntax && !usingStatementNode.OpenParenToken.IsMissing && !usingStatementNode.CloseParenToken.IsMissing && !WithinEmbeddedStatement(usingStatementNode, caretPosition); private static bool ShouldAddBraceForWhileStatement(WhileStatementSyntax whileStatementNode, int caretPosition) => whileStatementNode.Statement is not BlockSyntax && !whileStatementNode.OpenParenToken.IsMissing && !whileStatementNode.CloseParenToken.IsMissing && !WithinEmbeddedStatement(whileStatementNode, caretPosition); private static bool WithinAttributeLists(SyntaxNode node, int caretPosition) { var attributeLists = node.GetAttributeLists(); return attributeLists.Span.Contains(caretPosition); } private static bool WithinBraces(SyntaxNode? node, int caretPosition) { var (openBrace, closeBrace) = node.GetBraces(); return TextSpan.FromBounds(openBrace.SpanStart, closeBrace.Span.End).Contains(caretPosition); } private static bool WithinMethodBody(SyntaxNode node, int caretPosition) { if (node is BaseMethodDeclarationSyntax { Body: { } baseMethodBody }) { return baseMethodBody.Span.Contains(caretPosition); } if (node is LocalFunctionStatementSyntax { Body: { } localFunctionBody }) { return localFunctionBody.Span.Contains(caretPosition); } return false; } private static bool HasNoBrace(SyntaxNode node) { var (openBrace, closeBrace) = node.GetBraces(); return openBrace.IsKind(SyntaxKind.None) && closeBrace.IsKind(SyntaxKind.None) || openBrace.IsMissing && closeBrace.IsMissing; } private static bool WithinEmbeddedStatement(SyntaxNode node, int caretPosition) => node.GetEmbeddedStatement()?.Span.Contains(caretPosition) ?? false; #endregion #region ShouldRemoveBraceCheck private static bool ShouldRemoveBraces(SyntaxNode node, int caretPosition) => node switch { ObjectCreationExpressionSyntax objectCreationExpressionNode => ShouldRemoveBraceForObjectCreationExpression(objectCreationExpressionNode), AccessorDeclarationSyntax accessorDeclarationNode => ShouldRemoveBraceForAccessorDeclaration(accessorDeclarationNode, caretPosition), PropertyDeclarationSyntax propertyDeclarationNode => ShouldRemoveBraceForPropertyDeclaration(propertyDeclarationNode, caretPosition), EventDeclarationSyntax eventDeclarationNode => ShouldRemoveBraceForEventDeclaration(eventDeclarationNode, caretPosition), _ => false, }; /// <summary> /// Remove the braces if the ObjectCreationExpression has an empty Initializer. /// </summary> private static bool ShouldRemoveBraceForObjectCreationExpression(ObjectCreationExpressionSyntax objectCreationExpressionNode) { var initializer = objectCreationExpressionNode.Initializer; return initializer != null && initializer.Expressions.IsEmpty(); } // Only do this when it is an accessor in property // Since it is illegal to have something like // int this[int i] { get; set;} // event EventHandler Bar {add; remove;} private static bool ShouldRemoveBraceForAccessorDeclaration(AccessorDeclarationSyntax accessorDeclarationNode, int caretPosition) => accessorDeclarationNode.Body != null && accessorDeclarationNode.Body.Statements.IsEmpty() && accessorDeclarationNode.ExpressionBody == null && accessorDeclarationNode.Parent != null && accessorDeclarationNode.Parent.IsParentKind(SyntaxKind.PropertyDeclaration) && accessorDeclarationNode.Body.Span.Contains(caretPosition); private static bool ShouldRemoveBraceForPropertyDeclaration(PropertyDeclarationSyntax propertyDeclarationNode, int caretPosition) { // If a property just has an empty accessorList, like // int i $${ } // then remove the braces and change it to a field // int i; if (propertyDeclarationNode.AccessorList != null && propertyDeclarationNode.ExpressionBody == null) { var accessorList = propertyDeclarationNode.AccessorList; return accessorList.Span.Contains(caretPosition) && accessorList.Accessors.IsEmpty(); } return false; } private static bool ShouldRemoveBraceForEventDeclaration(EventDeclarationSyntax eventDeclarationNode, int caretPosition) { // If an event declaration just has an empty accessorList, // like // event EventHandler e$$ { } // then change it to a event field declaration // event EventHandler e; var accessorList = eventDeclarationNode.AccessorList; return accessorList != null && accessorList.Span.Contains(caretPosition) && accessorList.Accessors.IsEmpty(); } #endregion #region AddBrace private static AccessorListSyntax GetAccessorListNode(IEditorOptions editorOptions) => SyntaxFactory.AccessorList().WithOpenBraceToken(GetOpenBrace(editorOptions)).WithCloseBraceToken(GetCloseBrace(editorOptions)); private static InitializerExpressionSyntax GetInitializerExpressionNode(IEditorOptions editorOptions) => SyntaxFactory.InitializerExpression(SyntaxKind.ObjectInitializerExpression) .WithOpenBraceToken(GetOpenBrace(editorOptions)); private static BlockSyntax GetBlockNode(IEditorOptions editorOptions) => SyntaxFactory.Block().WithOpenBraceToken(GetOpenBrace(editorOptions)).WithCloseBraceToken(GetCloseBrace(editorOptions)); private static SyntaxToken GetOpenBrace(IEditorOptions editorOptions) => SyntaxFactory.Token( leading: SyntaxTriviaList.Empty, kind: SyntaxKind.OpenBraceToken, trailing: SyntaxTriviaList.Create(GetNewLineTrivia(editorOptions))) .WithAdditionalAnnotations(s_openBracePositionAnnotation); private static SyntaxToken GetCloseBrace(IEditorOptions editorOptions) => SyntaxFactory.Token( leading: SyntaxTriviaList.Empty, kind: SyntaxKind.CloseBraceToken, trailing: SyntaxTriviaList.Create(GetNewLineTrivia(editorOptions))); private static SyntaxTrivia GetNewLineTrivia(IEditorOptions editorOptions) { var newLineString = editorOptions.GetNewLineCharacter(); return SyntaxFactory.EndOfLine(newLineString); } /// <summary> /// Add braces to the <param name="node"/>. /// For FieldDeclaration and EventFieldDeclaration, it will change them to PropertyDeclaration and EventDeclaration /// </summary> private static SyntaxNode WithBraces(SyntaxNode node, IEditorOptions editorOptions) => node switch { BaseTypeDeclarationSyntax baseTypeDeclarationNode => WithBracesForBaseTypeDeclaration(baseTypeDeclarationNode, editorOptions), ObjectCreationExpressionSyntax objectCreationExpressionNode => GetObjectCreationExpressionWithInitializer(objectCreationExpressionNode, editorOptions), FieldDeclarationSyntax fieldDeclarationNode when fieldDeclarationNode.Declaration.Variables.IsSingle() => ConvertFieldDeclarationToPropertyDeclaration(fieldDeclarationNode, editorOptions), EventFieldDeclarationSyntax eventFieldDeclarationNode => ConvertEventFieldDeclarationToEventDeclaration(eventFieldDeclarationNode, editorOptions), BaseMethodDeclarationSyntax baseMethodDeclarationNode => AddBlockToBaseMethodDeclaration(baseMethodDeclarationNode, editorOptions), LocalFunctionStatementSyntax localFunctionStatementNode => AddBlockToLocalFunctionDeclaration(localFunctionStatementNode, editorOptions), AccessorDeclarationSyntax accessorDeclarationNode => AddBlockToAccessorDeclaration(accessorDeclarationNode, editorOptions), _ when node.IsEmbeddedStatementOwner() => AddBlockToEmbeddedStatementOwner(node, editorOptions), _ => throw ExceptionUtilities.UnexpectedValue(node), }; /// <summary> /// Add braces to <param name="baseTypeDeclarationNode"/>. /// </summary> private static BaseTypeDeclarationSyntax WithBracesForBaseTypeDeclaration( BaseTypeDeclarationSyntax baseTypeDeclarationNode, IEditorOptions editorOptions) => baseTypeDeclarationNode.WithOpenBraceToken(GetOpenBrace(editorOptions)) .WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken)); /// <summary> /// Add an empty initializer to <param name="objectCreationExpressionNode"/>. /// </summary> private static ObjectCreationExpressionSyntax GetObjectCreationExpressionWithInitializer( ObjectCreationExpressionSyntax objectCreationExpressionNode, IEditorOptions editorOptions) => objectCreationExpressionNode.WithInitializer(GetInitializerExpressionNode(editorOptions)); /// <summary> /// Convert <param name="fieldDeclarationNode"/> to a property declarations. /// </summary> private static PropertyDeclarationSyntax ConvertFieldDeclarationToPropertyDeclaration( FieldDeclarationSyntax fieldDeclarationNode, IEditorOptions editorOptions) => SyntaxFactory.PropertyDeclaration( fieldDeclarationNode.AttributeLists, fieldDeclarationNode.Modifiers, fieldDeclarationNode.Declaration.Type, explicitInterfaceSpecifier: null, identifier: fieldDeclarationNode.Declaration.Variables[0].Identifier, accessorList: GetAccessorListNode(editorOptions), expressionBody: null, initializer: null, semicolonToken: SyntaxFactory.Token(SyntaxKind.None)).WithTriviaFrom(fieldDeclarationNode); /// <summary> /// Convert <param name="eventFieldDeclarationNode"/> to an eventDeclaration node. /// </summary> private static EventDeclarationSyntax ConvertEventFieldDeclarationToEventDeclaration( EventFieldDeclarationSyntax eventFieldDeclarationNode, IEditorOptions editorOptions) => SyntaxFactory.EventDeclaration( eventFieldDeclarationNode.AttributeLists, eventFieldDeclarationNode.Modifiers, eventFieldDeclarationNode.EventKeyword, eventFieldDeclarationNode.Declaration.Type, explicitInterfaceSpecifier: null, identifier: eventFieldDeclarationNode.Declaration.Variables[0].Identifier, accessorList: GetAccessorListNode(editorOptions), semicolonToken: SyntaxFactory.Token(SyntaxKind.None)).WithTriviaFrom(eventFieldDeclarationNode); /// <summary> /// Add an empty block to <param name="baseMethodDeclarationNode"/>. /// </summary> private static BaseMethodDeclarationSyntax AddBlockToBaseMethodDeclaration( BaseMethodDeclarationSyntax baseMethodDeclarationNode, IEditorOptions editorOptions) => baseMethodDeclarationNode.WithBody(GetBlockNode(editorOptions)) // When the method declaration with no body is parsed, it has an invisible trailing semicolon. Make sure it is removed. .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); /// <summary> /// Add an empty block to <param name="localFunctionStatementNode"/>. /// </summary> private static LocalFunctionStatementSyntax AddBlockToLocalFunctionDeclaration( LocalFunctionStatementSyntax localFunctionStatementNode, IEditorOptions editorOptions) => localFunctionStatementNode.WithBody(GetBlockNode(editorOptions)) // When the local method declaration with no body is parsed, it has an invisible trailing semicolon. Make sure it is removed. .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); /// <summary> /// Add an empty block to <param name="accessorDeclarationNode"/>. /// </summary> private static AccessorDeclarationSyntax AddBlockToAccessorDeclaration( AccessorDeclarationSyntax accessorDeclarationNode, IEditorOptions editorOptions) => accessorDeclarationNode.WithBody(GetBlockNode(editorOptions)) // When the accessor with no body is parsed, it has an invisible trailing semicolon. Make sure it is removed. .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); /// <summary> /// Add a block with <param name="extraNodeInsertedBetweenBraces"/> to <param name="embeddedStatementOwner"/> /// </summary> private static SyntaxNode AddBlockToEmbeddedStatementOwner( SyntaxNode embeddedStatementOwner, IEditorOptions editorOptions, StatementSyntax? extraNodeInsertedBetweenBraces = null) { var block = extraNodeInsertedBetweenBraces != null ? GetBlockNode(editorOptions).WithStatements(new SyntaxList<StatementSyntax>(extraNodeInsertedBetweenBraces)) : GetBlockNode(editorOptions); return embeddedStatementOwner switch { DoStatementSyntax doStatementNode => doStatementNode.WithStatement(block), ForEachStatementSyntax forEachStatementNode => forEachStatementNode.WithStatement(block), ForStatementSyntax forStatementNode => forStatementNode.WithStatement(block), IfStatementSyntax ifStatementNode => ifStatementNode.WithStatement(block), ElseClauseSyntax elseClauseNode => elseClauseNode.WithStatement(block), WhileStatementSyntax whileStatementNode => whileStatementNode.WithStatement(block), UsingStatementSyntax usingStatementNode => usingStatementNode.WithStatement(block), LockStatementSyntax lockStatementNode => lockStatementNode.WithStatement(block), _ => throw ExceptionUtilities.UnexpectedValue(embeddedStatementOwner) }; } #endregion #region RemoveBrace /// <summary> /// Remove the brace for the input syntax node /// For ObjectCreationExpressionSyntax, it would remove the initializer /// For PropertyDeclarationSyntax, it would change it to a FieldDeclaration /// For EventDeclarationSyntax, it would change it to eventFieldDeclaration /// For Accessor, it would change it to the empty version ending with semicolon. /// e.g get {} => get; /// </summary> private static SyntaxNode WithoutBraces(SyntaxNode node) => node switch { ObjectCreationExpressionSyntax objectCreationExpressionNode => RemoveInitializerForObjectCreationExpression(objectCreationExpressionNode), PropertyDeclarationSyntax propertyDeclarationNode => ConvertPropertyDeclarationToFieldDeclaration(propertyDeclarationNode), EventDeclarationSyntax eventDeclarationNode => ConvertEventDeclarationToEventFieldDeclaration(eventDeclarationNode), AccessorDeclarationSyntax accessorDeclarationNode => RemoveBodyForAccessorDeclarationNode(accessorDeclarationNode), _ => throw ExceptionUtilities.UnexpectedValue(node), }; /// <summary> /// Remove the initializer for <param name="objectCreationExpressionNode"/>. /// </summary> private static ObjectCreationExpressionSyntax RemoveInitializerForObjectCreationExpression( ObjectCreationExpressionSyntax objectCreationExpressionNode) { var objectCreationNodeWithoutInitializer = objectCreationExpressionNode.WithInitializer(null); // Filter the non-comments trivia // e.g. // Bar(new Foo() // I am some comments // { // $$ // }); // => // Bar(new Foo() // I am some comments); // In this case, 'I am somme comments' has an end of line triva, if not removed, it would make // the final result becomes // Bar(new Foo() // I am some comments // ); var trivia = objectCreationNodeWithoutInitializer.GetTrailingTrivia().Where(trivia => trivia.IsSingleOrMultiLineComment()); return objectCreationNodeWithoutInitializer.WithTrailingTrivia(trivia); } /// <summary> /// Convert <param name="propertyDeclarationNode"/> to fieldDeclaration. /// </summary> private static FieldDeclarationSyntax ConvertPropertyDeclarationToFieldDeclaration( PropertyDeclarationSyntax propertyDeclarationNode) => SyntaxFactory.FieldDeclaration( propertyDeclarationNode.AttributeLists, propertyDeclarationNode.Modifiers, SyntaxFactory.VariableDeclaration( propertyDeclarationNode.Type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator(propertyDeclarationNode.Identifier))), SyntaxFactory.Token(SyntaxKind.SemicolonToken)); /// <summary> /// Convert <param name="eventDeclarationNode"/> to EventFieldDeclaration. /// </summary> private static EventFieldDeclarationSyntax ConvertEventDeclarationToEventFieldDeclaration( EventDeclarationSyntax eventDeclarationNode) => SyntaxFactory.EventFieldDeclaration( eventDeclarationNode.AttributeLists, eventDeclarationNode.Modifiers, SyntaxFactory.VariableDeclaration( eventDeclarationNode.Type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator(eventDeclarationNode.Identifier)))); /// <summary> /// Remove the body of <param name="accessorDeclarationNode"/>. /// </summary> private static AccessorDeclarationSyntax RemoveBodyForAccessorDeclarationNode(AccessorDeclarationSyntax accessorDeclarationNode) => accessorDeclarationNode .WithBody(null).WithoutTrailingTrivia().WithSemicolonToken( SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.SemicolonToken, SyntaxTriviaList.Empty)); #endregion } }
1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticLineEnderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AutomaticCompletion { [Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public class AutomaticLineEnderTests : AbstractAutomaticLineEnderTests { [WpfFact] public void Creation() { Test(@" $$", "$$"); } [WpfFact] public void Usings() { Test(@"using System; $$", @"using System$$"); } [WpfFact] public void Namespace() { Test(@"namespace {} $$", @"namespace {$$}"); } [WpfFact] public void Class() { Test(@"class {} $$", "class {$$}"); } [WpfFact] public void Method() { Test(@"class C { void Method() {$$} }", @"class C { void Method() {$$} }", assertNextHandlerInvoked: true); } [WpfFact] public void Field() { Test(@"class C { private readonly int i = 3; $$ }", @"class C { pri$$vate re$$adonly i$$nt i = 3$$ }"); } [WpfFact] public void EventField() { Test(@"class C { event System.EventHandler e = null; $$ }", @"class C { e$$vent System.Even$$tHandler e$$ = null$$ }"); } [WpfFact] public void Field2() { Test(@"class C { private readonly int i; $$ }", @"class C { private readonly int i$$ }"); } [WpfFact] public void EventField2() { Test(@"class C { event System.EventHandler e { $$ } }", @"class C { eve$$nt System.E$$ventHandler e$$ }"); } [WpfFact] public void Field3() { Test(@"class C { private readonly int $$ }", @"class C { private readonly int$$ }"); } [WpfFact] public void EventField3() { Test(@"class C { event System.EventHandler $$ }", @"class C { event System.EventHandler$$ }"); } [WpfFact] public void EmbededStatement() { Test(@"class C { void Method() { if (true) { $$ } } }", @"class C { void Method() { if (true) $$ } }"); } [WpfFact] public void EmbededStatement1() { Test(@"class C { void Method() { if (true) Console.WriteLine() $$ } }", @"class C { void Method() { if (true) Console.WriteLine()$$ } }"); } [WpfFact] public void EmbededStatement2() { Test(@"class C { void Method() { if (true) Console.WriteLine(); $$ } }", @"class C { void Method() { if (true) Console.WriteLine($$) } }"); } [WpfFact] public void Statement() { Test(@"class C { void Method() { int i; $$ } }", @"class C { void Method() { int i$$ } }"); } [WpfFact] public void Statement1() { Test(@"class C { void Method() { int $$ } }", @"class C { void Method() { int$$ } }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedMethod() { Test(@"class T { int M() => 1 + 2; $$ }", @"class T { int M() => 1 + 2$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedOperator() { Test(@"class Complex { int real; int imaginary; public static Complex operator +(Complex a, Complex b) => a.Add(b.real + 1); $$ private Complex Add(int b) => null; }", @"class Complex { int real; int imaginary; public static Complex operator +(Complex a, Complex b) => a.Add(b.real + 1)$$ private Complex Add(int b) => null; }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedConversionOperator() { Test(@"using System; public struct DBBool { public static readonly DBBool dbFalse = new DBBool(-1); int value; DBBool(int value) { this.value = value; } public static implicit operator DBBool(bool x) => x ? new DBBool(1) : dbFalse; $$ }", @"using System; public struct DBBool { public static readonly DBBool dbFalse = new DBBool(-1); int value; DBBool(int value) { this.value = value; } public static implicit operator DBBool(bool x) => x ? new DBBool(1) : dbFalse$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedProperty() { Test(@"class T { int P1 => 1 + 2; $$ }", @"class T { int P1 => 1 + 2$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedIndexer() { Test(@"using System; class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] => i > 0 ? arr[i + 1] : arr[i + 2]; $$ }", @"using System; class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] => i > 0 ? arr[i + 1] : arr[i + 2]$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedMethodWithBlockBodiedAnonymousMethodExpression() { Test(@"using System; class TestClass { Func<int, int> Y() => delegate (int x) { return 9; }; $$ }", @"using System; class TestClass { Func<int, int> Y() => delegate (int x) { return 9; }$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedMethodWithSingleLineBlockBodiedAnonymousMethodExpression() { Test(@"using System; class TestClass { Func<int, int> Y() => delegate (int x) { return 9; }; $$ }", @"using System; class TestClass { Func<int, int> Y() => delegate (int x) { return 9; }$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedMethodWithBlockBodiedSimpleLambdaExpression() { Test(@"using System; class TestClass { Func<int, int> Y() => f => { return f * 9; }; $$ }", @"using System; class TestClass { Func<int, int> Y() => f => { return f * 9; }$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedMethodWithExpressionBodiedSimpleLambdaExpression() { Test(@"using System; class TestClass { Func<int, int> Y() => f => f * 9; $$ }", @"using System; class TestClass { Func<int, int> Y() => f => f * 9$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedMethodWithBlockBodiedAnonymousMethodExpressionInMethodArgs() { Test(@"using System; class TestClass { public int Prop => Method1(delegate () { return 8; }); $$ private int Method1(Func<int> p) => null; }", @"using System; class TestClass { public int Prop => Method1(delegate() { return 8; })$$ private int Method1(Func<int> p) => null; }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void Format_SimpleExpressionBodiedMember() { Test(@"class T { int M() => 1 + 2; $$ }", @"class T { int M() => 1 + 2$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void Format_ExpressionBodiedMemberWithSingleLineBlock() { Test(@"using System; class TestClass { Func<int, int> Y() => delegate (int x) { return 9; }; $$ }", @"using System; class TestClass { Func<int, int> Y () => delegate(int x) { return 9 ; }$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void Format_ExpressionBodiedMemberWithMultiLineBlock() { Test(@"using System; class TestClass { Func<int, int> Y() => delegate (int x) { return 9; }; $$ }", @"using System; class TestClass { Func<int, int> Y() => delegate(int x) { return 9; }$$ }"); } [WpfFact] public void Format_Statement() { Test(@"class C { void Method() { int i = 1; $$ } }", @"class C { void Method() { int i = 1 $$ } }"); } [WpfFact] public void Format_Using() { Test(@"using System.Linq; $$", @" using System . Linq $$"); } [WpfFact] public void Format_Using2() { Test(@"using System.Linq; $$", @" using System . Linq $$"); } [WpfFact] public void Format_Field() { Test(@"class C { int i = 1; $$ }", @"class C { int i = 1 $$ }"); } [WpfFact] public void Statement_Trivia() { Test(@"class C { void goo() { goo(); //comment $$ } }", @"class C { void goo() { goo()$$ //comment } }"); } [WpfFact] public void TrailingText_Negative() { Test(@"class C { event System.EventHandler e = null int i = 2; $$ }", @"class C { event System.EventHandler e = null$$ int i = 2; }"); } [WpfFact] public void CompletionSetUp() { Test(@"class Program { object goo(object o) { return goo(); $$ } }", @"class Program { object goo(object o) { return goo($$) } }", completionActive: true); } [WorkItem(530352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530352")] [WpfFact] public void EmbededStatement3() { Test(@"class Program { void Method() { foreach (var x in y) { $$ } } }", @"class Program { void Method() { foreach (var x in y$$) } }"); } [WorkItem(530716, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530716")] [WpfFact] public void DontAssertOnMultilineToken() { Test(@"interface I { void M(string s = @"""""" $$ }", @"interface I { void M(string s = @""""""$$ }"); } [WorkItem(530718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530718")] [WpfFact] public void AutomaticLineFormat() { Test(@"class C { public string P { set; get; } $$ }", @"class C { public string P {set;get;$$} }"); } [WpfFact] public void NotAfterExisitingSemicolon() { Test(@"class TestClass { private int i; $$ }", @"class TestClass { private int i;$$ }"); } [WpfFact] public void NotAfterCloseBraceInMethod() { Test(@"class TestClass { void Test() { } $$ }", @"class TestClass { void Test() { }$$ }"); } [WpfFact] public void NotAfterCloseBraceInStatement() { Test(@"class TestClass { void Test() { if (true) { } $$ } }", @"class TestClass { void Test() { if (true) { }$$ } }"); } [WpfFact] public void NotAfterAutoPropertyAccessor() { Test(@"class TestClass { public int A { get; set } $$ }", @"class TestClass { public int A { get; set$$ } }"); } [WpfFact] public void NotAfterAutoPropertyDeclaration() { Test(@"class TestClass { public int A { get; set; } $$ }", @"class TestClass { public int A { get; set; }$$ }"); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void DelegatedInEmptyBlock() { Test(@"class TestClass { void Method() { try { $$} } }", @"class TestClass { void Method() { try { $$} } }", assertNextHandlerInvoked: true); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void DelegatedInEmptyBlock2() { Test(@"class TestClass { void Method() { if (true) { $$} } }", @"class TestClass { void Method() { if (true) { $$} } }", assertNextHandlerInvoked: true); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void NotDelegatedOutsideEmptyBlock() { Test(@"class TestClass { void Method() { try { } $$ } }", @"class TestClass { void Method() { try { }$$ } }"); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void NotDelegatedAfterOpenBraceAndMissingCloseBrace() { Test(@"class TestClass { void Method() { try { $$ } }", @"class TestClass { void Method() { try {$$ } }"); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void NotDelegatedInNonEmptyBlock() { Test(@"class TestClass { void Method() { try { x } $$ } }", @"class TestClass { void Method() { try { x$$ } } }"); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void NotDelegatedAfterOpenBraceInAnonymousObjectCreationExpression() { Test(@"class TestClass { void Method() { var pet = new { }; $$ } }", @"class TestClass { void Method() { var pet = new { $$} } }"); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void NotDelegatedAfterOpenBraceObjectCreationExpression() { Test(@"class TestClass { void Method() { var pet = new List<int>(); $$ } }", @"class TestClass { void Method() { var pet = new List<int> { $$} } }"); } [WpfFact] public void TestMulitpleNamespace() { Test($@" namespace Bar2 {{ $$ }} namespace Bar {{ }}", $@" namespace B$$ar2$$ namespace Bar {{ }}"); } [WpfTheory] [InlineData("namespace")] [InlineData("class")] [InlineData("struct")] [InlineData("record")] [InlineData("enum")] [InlineData("interface")] public void TestEmptyBaseTypeDeclarationAndNamespace(string typeKeyword) { Test($@" public {typeKeyword} Bar {{ $$ }}", $@" pu$$blic {typeKeyword} $$Bar$$"); } [WpfTheory] [InlineData("class")] [InlineData("struct")] [InlineData("record")] [InlineData("enum")] [InlineData("interface")] public void TestMultipleBaseTypeDeclaration(string typeKeyword) { Test($@" public {typeKeyword} Bar2 {{ $$ }} public {typeKeyword} Bar {{ }}", $@" pub$$lic {typeKeyword} B$$ar2$$ public {typeKeyword} Bar {{ }}"); } [WpfFact] public void TestNestedTypeDeclaration() { Test(@" public class Bar1 { public class Bar2 { $$ } }", @" public class Bar1 { pu$$blic cla$$ss B$$ar2$$ }"); } [WpfFact] public void TestNestedNamespace() { Test(@" namespace Bar1 { namespace Bar2 { $$ } }", @" namespace Bar1 { namespa$$ce $$B$$ar2$$ }"); } [WpfTheory] [InlineData("namespace")] [InlineData("class")] [InlineData("struct")] [InlineData("record")] [InlineData("enum")] [InlineData("interface")] public void TestBaseTypeDeclarationAndNamespaceWithOpenBrace(string typeKeyword) { Test($@" public {typeKeyword} Bar {{ $$", $@" pub$$lic {typeKeyword} B$$ar {{$$"); } [WpfTheory] [InlineData("namespace")] [InlineData("class")] [InlineData("struct")] [InlineData("record")] [InlineData("enum")] [InlineData("interface")] public void TestValidTypeDeclarationAndNamespace(string typeKeyword) { Test($@"public {typeKeyword} Bar {{}} $$", $@"public {typeKeyword}$$ Ba$$r {{}}$$"); } [WpfFact] public void TestMethod() { Test(@" public class Bar { void Main() { $$ } }", @" public class Bar { v$$oid Ma$$in($$)$$ }"); } [WpfFact] public void TestConstructor() { Test(@" public class Bar { void Bar() { $$ } }", @" public class Bar { v$$oid Ba$$r($$)$$ }"); } [WpfFact] public void TestValidMethodInInterface() { Test(@" public interface Bar { void Main(); $$ }", @" public interface Bar { v$$oid Mai$$n($$)$$; }"); } [WpfFact] public void TestMissingSemicolonMethodInInterface() { Test(@" public interface Bar { void Main() $$ }", @" public interface Bar { v$$oid Mai$$n($$)$$ }"); } [WpfFact] public void TestValidLocalFunction() { Test(@" public class Bar { void Main() { void Local() $$ { } } }", @" public class Bar { void Main() { v$$oid Loc$$al($$)$$ { } } }"); } [WpfFact] public void TestLocalFunction() { Test(@" public class Bar { void Main() { void Local() { $$ } } }", @" public class Bar { void Main() { v$$oid Loca$$l($$)$$ } }"); } [WpfFact] public void TestIndexerAsLastElementInClass() { Test(@" public class Bar { public int this[int i] { $$ } }", @" public class Bar { p$$ublic in$$t thi$$s[in$$t i]$$ }"); } [WpfFact] public void TestIndexerNotAsLastElementInClass() { Test(@" public class Bar { public int this[int i] { $$ } void Main() {} }", @" public class Bar { p$$ublic in$$t thi$$s[in$$t i]$$ void Main() {} }"); } [WpfFact] public void TestValidIndexer() { Test(@" public class Bar { public int this[int i] $$ { } }", @" public class Bar { p$$ublic i$$nt thi$$s[in$$t i]$$ { } }"); } [WpfFact] public void TestGetAccessorOfProperty() { var initialMarkup = @" public class Bar { public int P { ge$$t } }"; var firstResult = @" public class Bar { public int P { get { $$ } } }"; var secondResult = @" public class Bar { public int P { get; $$ } }"; Test(firstResult, initialMarkup); Test(secondResult, firstResult); } [WpfFact] public void TestSetAccessorOfProperty() { var initialMarkup = @" public class Bar { public int P { set$$ } }"; var firstResult = @" public class Bar { public int P { set { $$ } } }"; var secondResult = @" public class Bar { public int P { set; $$ } }"; Test(firstResult, initialMarkup); Test(secondResult, firstResult); } [WpfFact] public void TestGetAccessorOfIndexer() { Test(@" public class Bar { public int this[int i] { get { $$ } } }", @" public class Bar { public int this[int i] { ge$$t } }"); } [WpfFact] public void TestValidGetAccessorOfIndexer() { Test(@" public class Bar { public int this[int i] { get { $$ } } }", @" public class Bar { public int this[int i] { get { $$ } } }"); } [WpfFact] public void TestNonEmptyGetAccessor() { Test(@" public Class Bar { public int P { get { if (true) $$ { return 1; } } } }", @" public Class Bar { public int P { get { i$$f ($$true$$)$$ { return 1; } } } }"); } [WpfFact] public void TestNonEmptySetAccessor() { Test(@" public Class Bar { public int P { get; set { if (true) $$ { } } } }", @" public Class Bar { public int P { get; set { i$$f (t$$rue)$$ { } } } }"); } [WpfFact] public void TestSetAccessorOfIndexer() { Test(@" public class Bar { public int this[int i] { get; set { $$ } } }", @" public class Bar { public int this[int i] { get; se$$t } }"); } [WpfFact] public void TestValidSetAccessorOfIndexer() { Test(@" public class Bar { public int this[int i] { get; set { $$ } } }", @" public class Bar { public int this[int i] { get; set { $$ } } }"); } [WpfFact] public void TestAddAccessorInEventDeclaration() { Test(@" using System; public class Bar { public event EventHandler e { add { $$ } remove } }", @" using System; public class Bar { public event EventHandler e { ad$$d remove } }"); } [WpfFact] public void TestValidAddAccessorInEventDeclaration() { Test(@" using System; public class Bar { public event EventHandler e { add { $$ } remove { } } }", @" using System; public class Bar { public event EventHandler e { add { $$ } remove { } } }"); } [WpfFact] public void TestRemoveAccessor() { Test(@" using System; public class Bar { public event EventHandler e { add remove { $$ } } }", @" using System; public class Bar { public event EventHandler e { add remo$$ve } }"); } [WpfFact] public void TestValidRemoveAccessor() { Test(@" using System; public class Bar { public event EventHandler e { add { } remove { $$ } } }", @" using System; public class Bar { public event EventHandler e { add { } remove { $$ } } }"); } [WpfFact] public void TestField() { var initialMarkup = @" public class Bar { p$$ublic i$$nt i$$ii$$ }"; var firstResult = @" public class Bar { public int iii { $$ } }"; var secondResult = @" public class Bar { public int iii; $$ }"; Test(firstResult, initialMarkup); Test(secondResult, firstResult); } [WpfFact] public void TestReadonlyField() { Test(@" public class Bar { public readonly int iii; $$ }", @" public class Bar { p$$ublic reado$$nly i$$nt i$$ii$$ }"); } [WpfFact] public void TestNonEmptyProperty() { Test(@" public class Bar { public int Foo { get { } $$ } }", @" public class Bar { public int Foo { $$get$$ { }$$ } }"); } [WpfFact] public void TestMulitpleFields() { Test(@" public class Bar { public int apple, banana; $$ }", @" public class Bar { p$$ublic i$$nt ap$$ple$$, ba$$nana;$$ }"); } [WpfFact] public void TestMultipleEvents() { Test(@" using System; public class Bar { public event EventHandler apple, banana; $$ }", @" using System; public class Bar { p$$ublic event EventHandler ap$$ple$$, ba$$nana$$;$$ }"); } [WpfFact] public void TestEvent() { var initialMarkup = @" using System; public class Bar { pu$$blic e$$vent EventHand$$ler c$$c$$ }"; var firstResult = @" using System; public class Bar { public event EventHandler cc { $$ } }"; var secondResult = @" using System; public class Bar { public event EventHandler cc; $$ }"; Test(firstResult, initialMarkup); Test(secondResult, firstResult); } [WpfFact] public void TestNonEmptyEvent() { Test(@" using System; public class Bar { public event EventHandler Foo { add { } $$ } }", @" using System; public class Bar { public event EventHandler Foo { $$add$$ {$$ }$$ } }"); } [WpfFact] public void TestObjectCreationExpressionWithParenthesis() { var initialMarkup = @" public class Bar { public void M() { var f = n$$ew F$$oo($$)$$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var firstResult = @" public class Bar { public void M() { var f = new Foo() { $$ }; } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var secondResult = @" public class Bar { public void M() { var f = new Foo(); $$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; Test(firstResult, initialMarkup); Test(secondResult, firstResult); } [WpfFact] public void TestObjectCreationExpressionWithNoParenthesis() { var initialMarkUp = @" public class Bar { public void M() { var f = n$$ew F$$oo$$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var firstResult = @" public class Bar { public void M() { var f = new Foo() { $$ }; } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var secondResult = @" public class Bar { public void M() { var f = new Foo(); $$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; Test(firstResult, initialMarkUp); Test(secondResult, firstResult); } [WpfFact] public void TestObjectCreationExpressionWithCorrectSemicolon() { var initialMarkUp = @" public class Bar { public void M() { var f = n$$ew F$$oo$$; } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var firstResult = @" public class Bar { public void M() { var f = new Foo() { $$ }; } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var secondResult = @" public class Bar { public void M() { var f = new Foo(); $$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; Test(firstResult, initialMarkUp); Test(secondResult, firstResult); } [WpfFact] public void TestObjectCreationExpressionUsedAsExpression() { var initialMarkUp = @" public class Bar { public void M() { N(ne$$w Fo$$o$$); } private void N(Foo f) { } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var firstResult = @" public class Bar { public void M() { N(new Foo() { $$ }); } private void N(Foo f) { } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var secondResult = @" public class Bar { public void M() { N(new Foo()); $$ } private void N(Foo f) { } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; Test(firstResult, initialMarkUp); Test(secondResult, firstResult); } [WpfFact] public void TestObjectCreationExpressionInUsingStatement() { var initialMarkup = @" public class Bar { public void M() { using(var a = n$$ew F$$oo($$)$$) } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var firstResult = @" public class Bar { public void M() { using(var a = new Foo() { $$ }) } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var secondResult = @" public class Bar { public void M() { using(var a = new Foo()) $$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; Test(firstResult, initialMarkup); Test(secondResult, firstResult); } [WpfFact] public void TestObjectCreationExpressionWithNonEmptyInitializer() { Test( @" public class Bar { public void M() { var a = new Foo() { HH = 1, PP = 2 }; $$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }", @" public class Bar { public void M() { var a = n$$ew Fo$$o($$) {$$ HH = 1$$, PP = 2 $$}; } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"); } [WpfFact] public void TestIfStatementWithInnerStatement() { Test(@" public class Bar { public void Main(bool x) { if (x) { $$ } var z = 1; } }", @" public class Bar { public void Main(bool x) { i$$f$$ ($$x)$$ var z = 1; } }"); } [WpfFact] public void TestIfStatementWithFollowingElseClause() { Test(@" public class Bar { public void Main(bool x) { if (x) { $$ var z = 1; } else if (!x) } }", @" public class Bar { public void Main(bool x) { i$$f$$ ($$x)$$ var z = 1; else if (!x) } }"); } [WpfFact] public void TestIfStatementWithoutStatement() { Test(@" public class Bar { public void Main(bool x) { if (x) { $$ } } }", @" public class Bar { public void Main(bool x) { i$$f$$ ($$x)$$ } }"); } [WpfFact] public void TestNestIfStatementWithInnerStatement() { Test(@" public class Bar { public void Main(int x) { if (x == 1) if (x == 2) if (x == 3) if (x == 4) { $$ var a = 1000; } } }", @" public class Bar { public void Main(int x) { if (x == 1) if (x == 2) if (x == 3) i$$f ($$x =$$= 4)$$ var a = 1000; } }"); } [WpfFact] public void TestNestIfStatementWithoutInnerStatement() { Test(@" public class Bar { public void Main(int x) { if (x == 1) if (x == 2) if (x == 3) if (x == 4) { $$ } } }", @" public class Bar { public void Main(int x) { if (x == 1) if (x == 2) if (x == 3) i$$f ($$x =$$= 4)$$ } }"); } [WpfFact] public void TestNestedElseIfStatementWithInnerStatement() { Test(@" public class Bar { public void Fo(int i) { if (i == 1) { } else if (i == 2) if (i == 3) { $$ var i = 10; } else { } } }", @" public class Bar { public void Fo(int i) { if (i == 1) { } else if (i == 2) i$$f (i$$ == 3)$$ var i = 10; else { } } }"); } [WpfFact] public void TestNestIfElseStatementWithBlockWithInnerStatement() { Test(@" public class Bar { public void Main(int x) { if (x == 1) if (x == 2) if (x == 3) { if (x == 4) { $$ } var i = 10; } else { } } }", @" public class Bar { public void Main(int x) { if (x == 1) if (x == 2) if (x == 3) { i$$f ($$x =$$= 4)$$ var i = 10; } else { } } }"); } [WpfFact] public void TestEmptyDoStatement() { Test(@" public class Bar { public void Main() { do { $$ } } }", @" public class Bar { public void Main() { d$$o$$ } }"); } [WpfFact] public void TestDoStatementWithInnerStatement() { Test(@" public class Bar { public void Main() { do { $$ } var c = 10; } }", @" public class Bar { public void Main() { d$$o$$ var c = 10; } }"); } [WpfFact] public void TestDoStatementWithWhileClause() { Test(@" public class Bar { public void Main() { do { $$ var c = 10; } while (true); } }", @" public class Bar { public void Main() { d$$o$$ var c = 10; while (true); } }"); } [WpfFact] public void TestSingleElseStatement() { Test(@" public class Bar { public void Fo() { if (true) { } else { $$ } } }", @" public class Bar { public void Fo() { if (true) { } e$$lse$$ } }"); } [WpfFact] public void TestElseStatementWithInnerStatement() { Test(@" public class Bar { public void Fo() { if (true) { } else { $$ } var c = 10; } }", @" public class Bar { public void Fo() { if (true) { } e$$lse$$ var c = 10; } }"); } [WpfFact] public void TestElseIfStatement() { Test(@" public class Bar { public void Fo() { if (true) { } else if (false) { $$ } } }", @" public class Bar { public void Fo() { if (true) { } e$$lse i$$f ($$false)$$ } }"); } [WpfFact] public void TestElseIfInTheMiddleWithInnerStatement() { Test(@" public class Bar { public void Fo() { if (true) { } else if (false) { $$ var i = 10; } else { } } }", @" public class Bar { public void Fo() { if (true) { } e$$lse i$$f ($$false)$$ var i = 10; else { } } }"); } [WpfFact] public void TestElseClauseInNestedIfStatement() { Test(@" public class Bar { public void Fo(int i) { if (i == 1) { if (i == 2) var i = 10; else { $$ } var c = 100; } } }", @" public class Bar { public void Fo(int i) { if (i == 1) { if (i == 2) var i = 10; el$$se var c = 100; } } }"); } [WpfFact] public void TestForStatementWithoutStatement() { Test(@" public class Bar { public void Fo() { for (int i; i < 10; i++) { $$ } } }", @" public class Bar { public void Fo() { f$$or (i$$nt i; i < 10;$$ i++)$$ } }"); } [WpfFact] public void TestForStatementWithInnerStatement() { Test(@" public class Bar { public void Fo() { for (int i; i < 10; i++) { $$ } var c = 10; } }", @" public class Bar { public void Fo() { f$$or (i$$nt i; i < 10;$$ i++)$$ var c = 10; } }"); } [WpfFact] public void TestForEachStatementWithoutInnerStatement() { Test(@" public class Bar { public void Fo() { foreach (var x in """") { $$ } var c = 10; } }", @" public class Bar { public void Fo() { forea$$ch (var x $$in """")$$ var c = 10; } }"); } [WpfFact] public void TestLockStatementWithoutInnerStatement() { Test(@" public class Bar { object o = new object(); public void Fo() { lock (o) { $$ } } }", @" public class Bar { object o = new object(); public void Fo() { l$$ock$$(o)$$ } }"); } [WpfFact] public void TestLockStatementWithInnerStatement() { Test(@" public class Bar { object o = new object(); public void Fo() { lock (o) { $$ } var i = 10; } }", @" public class Bar { object o = new object(); public void Fo() { l$$ock$$(o)$$ var i = 10; } }"); } [WpfFact] public void TestUsingStatementWithoutInnerStatement() { Test(@" using System; public class Bar { public void Fo() { using (var d = new D()) { $$ } } } public class D : IDisposable { public void Dispose() {} }", @" using System; public class Bar { public void Fo() { usi$$ng (va$$r d = new D())$$ } } public class D : IDisposable { public void Dispose() {} }"); } [WpfFact] public void TestUsingStatementWithInnerStatement() { Test(@" using System; public class Bar { public void Fo() { using (var d = new D()) { $$ } var c = 10; } } public class D : IDisposable { public void Dispose() {} }", @" using System; public class Bar { public void Fo() { usi$$ng (va$$r d = new D())$$ var c = 10; } } public class D : IDisposable { public void Dispose() {} }"); } [WpfFact] public void TestUsingInLocalDeclarationStatement() { Test(@" using System; public class Bar { public void Fo() { using var d = new D(); $$ } } public class D : IDisposable { public void Dispose() {} }", @" using System; public class Bar { public void Fo() { usi$$ng v$$ar$$ d = new D() } } public class D : IDisposable { public void Dispose() {} }"); } [WpfFact] public void TestWhileStatementWithoutInnerStatement() { Test(@" public class Bar { public void Fo() { while (true) { $$ } } }", @" public class Bar { public void Fo() { wh$$ile (tr$$ue)$$ } }"); } [WpfFact] public void TestWhileStatementWithInnerStatement() { Test(@" public class Bar { public void Fo() { while (true) { $$ } var c = 10; } }", @" public class Bar { public void Fo() { wh$$ile (tr$$ue)$$ var c = 10; } }"); } [WpfFact] public void TestSwitchStatement() { Test(@" public class bar { public void TT() { int i = 10; switch (i) { $$ } } }", @" public class bar { public void TT() { int i = 10; switc$$h ($$i)$$ } }"); } [WpfFact] public void TestValidSwitchStatement() { Test(@" public class bar { public void TT() { int i = 10; switch (i) $$ { } } }", @" public class bar { public void TT() { int i = 10; switc$$h ($$i)$$ { } } }"); } [WpfFact] public void TestValidTryStatement() { Test(@" public class bar { public void TT() { try $$ { } } }", @" public class bar { public void TT() { tr$$y$$ { } } }"); } [WpfFact] public void TestTryStatement() { Test(@" public class bar { public void TT() { try { $$ } } }", @" public class bar { public void TT() { tr$$y$$ } }"); } [WpfFact] public void TestValidCatchClause() { Test(@" public class Bar { public void TT() { try { } catch (System.Exception) $$ { } } }", @" public class Bar { public void TT() { try { } cat$$ch (Syste$$m.Exception)$$ { } } }"); } [WpfFact] public void TestCatchClauseWithException() { Test(@" public class Bar { public void TT() { try { } catch (System.Exception) { $$ } } }", @" public class Bar { public void TT() { try { } cat$$ch (Syste$$m.Exception)$$ } }"); } [WpfFact] public void TestSingleCatchClause() { Test(@" public class bar { public void TT() { try { } catch { $$ } } }", @" public class bar { public void TT() { try { } cat$$ch$$ } }"); } [WpfFact] public void TestCatchClauseWithWhenClause() { Test(@" public class bar { public void TT() { try { } catch (Exception) when (true) { $$ } } }", @" public class bar { public void TT() { try { } c$$atch (Ex$$ception) whe$$n (tru$$e)$$ } }"); } [WpfFact] public void TestFinallyCaluse() { Test(@" public class Bar { public void Bar2() { try { } catch (System.Exception) { } finally { $$ } } }", @" public class Bar { public void Bar2() { try { } catch (System.Exception) { } fin$$ally$$ } }"); } [WpfFact] public void TestValidFinallyCaluse() { Test(@" public class Bar { public void Bar2() { try { } catch (System.Exception) { } finally $$ { } } }", @" public class Bar { public void Bar2() { try { } catch (System.Exception) { } fin$$ally { } } }"); } protected override string Language => LanguageNames.CSharp; protected override Action CreateNextHandler(TestWorkspace workspace) => () => { }; internal override IChainedCommandHandler<AutomaticLineEnderCommandArgs> GetCommandHandler(TestWorkspace workspace) { return Assert.IsType<AutomaticLineEnderCommandHandler>( workspace.GetService<ICommandHandler>( ContentTypeNames.CSharpContentType, PredefinedCommandHandlerNames.AutomaticLineEnder)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AutomaticCompletion { [Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public class AutomaticLineEnderTests : AbstractAutomaticLineEnderTests { [WpfFact] public void Creation() { Test(@" $$", "$$"); } [WpfFact] public void Usings() { Test(@"using System; $$", @"using System$$"); } [WpfFact] public void Namespace() { Test(@"namespace {} $$", @"namespace {$$}"); } [WpfFact] public void Class() { Test(@"class {} $$", "class {$$}"); } [WpfFact] public void Method() { Test(@"class C { void Method() {$$} }", @"class C { void Method() {$$} }", assertNextHandlerInvoked: true); } [WpfFact] public void Field() { Test(@"class C { private readonly int i = 3; $$ }", @"class C { pri$$vate re$$adonly i$$nt i = 3$$ }"); } [WpfFact] public void EventField() { Test(@"class C { event System.EventHandler e = null; $$ }", @"class C { e$$vent System.Even$$tHandler e$$ = null$$ }"); } [WpfFact] public void Field2() { Test(@"class C { private readonly int i; $$ }", @"class C { private readonly int i$$ }"); } [WpfFact] public void EventField2() { Test(@"class C { event System.EventHandler e { $$ } }", @"class C { eve$$nt System.E$$ventHandler e$$ }"); } [WpfFact] public void Field3() { Test(@"class C { private readonly int $$ }", @"class C { private readonly int$$ }"); } [WpfFact] public void EventField3() { Test(@"class C { event System.EventHandler $$ }", @"class C { event System.EventHandler$$ }"); } [WpfFact] public void EmbededStatement() { Test(@"class C { void Method() { if (true) { $$ } } }", @"class C { void Method() { if (true) $$ } }"); } [WpfFact] public void EmbededStatement1() { Test(@"class C { void Method() { if (true) Console.WriteLine() $$ } }", @"class C { void Method() { if (true) Console.WriteLine()$$ } }"); } [WpfFact] public void EmbededStatement2() { Test(@"class C { void Method() { if (true) Console.WriteLine(); $$ } }", @"class C { void Method() { if (true) Console.WriteLine($$) } }"); } [WpfFact] public void Statement() { Test(@"class C { void Method() { int i; $$ } }", @"class C { void Method() { int i$$ } }"); } [WpfFact] public void Statement1() { Test(@"class C { void Method() { int $$ } }", @"class C { void Method() { int$$ } }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedMethod() { Test(@"class T { int M() => 1 + 2; $$ }", @"class T { int M() => 1 + 2$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedOperator() { Test(@"class Complex { int real; int imaginary; public static Complex operator +(Complex a, Complex b) => a.Add(b.real + 1); $$ private Complex Add(int b) => null; }", @"class Complex { int real; int imaginary; public static Complex operator +(Complex a, Complex b) => a.Add(b.real + 1)$$ private Complex Add(int b) => null; }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedConversionOperator() { Test(@"using System; public struct DBBool { public static readonly DBBool dbFalse = new DBBool(-1); int value; DBBool(int value) { this.value = value; } public static implicit operator DBBool(bool x) => x ? new DBBool(1) : dbFalse; $$ }", @"using System; public struct DBBool { public static readonly DBBool dbFalse = new DBBool(-1); int value; DBBool(int value) { this.value = value; } public static implicit operator DBBool(bool x) => x ? new DBBool(1) : dbFalse$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedProperty() { Test(@"class T { int P1 => 1 + 2; $$ }", @"class T { int P1 => 1 + 2$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedIndexer() { Test(@"using System; class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] => i > 0 ? arr[i + 1] : arr[i + 2]; $$ }", @"using System; class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] => i > 0 ? arr[i + 1] : arr[i + 2]$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedMethodWithBlockBodiedAnonymousMethodExpression() { Test(@"using System; class TestClass { Func<int, int> Y() => delegate (int x) { return 9; }; $$ }", @"using System; class TestClass { Func<int, int> Y() => delegate (int x) { return 9; }$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedMethodWithSingleLineBlockBodiedAnonymousMethodExpression() { Test(@"using System; class TestClass { Func<int, int> Y() => delegate (int x) { return 9; }; $$ }", @"using System; class TestClass { Func<int, int> Y() => delegate (int x) { return 9; }$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedMethodWithBlockBodiedSimpleLambdaExpression() { Test(@"using System; class TestClass { Func<int, int> Y() => f => { return f * 9; }; $$ }", @"using System; class TestClass { Func<int, int> Y() => f => { return f * 9; }$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedMethodWithExpressionBodiedSimpleLambdaExpression() { Test(@"using System; class TestClass { Func<int, int> Y() => f => f * 9; $$ }", @"using System; class TestClass { Func<int, int> Y() => f => f * 9$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void ExpressionBodiedMethodWithBlockBodiedAnonymousMethodExpressionInMethodArgs() { Test(@"using System; class TestClass { public int Prop => Method1(delegate () { return 8; }); $$ private int Method1(Func<int> p) => null; }", @"using System; class TestClass { public int Prop => Method1(delegate() { return 8; })$$ private int Method1(Func<int> p) => null; }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void Format_SimpleExpressionBodiedMember() { Test(@"class T { int M() => 1 + 2; $$ }", @"class T { int M() => 1 + 2$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void Format_ExpressionBodiedMemberWithSingleLineBlock() { Test(@"using System; class TestClass { Func<int, int> Y() => delegate (int x) { return 9; }; $$ }", @"using System; class TestClass { Func<int, int> Y () => delegate(int x) { return 9 ; }$$ }"); } [WorkItem(3944, "https://github.com/dotnet/roslyn/issues/3944")] [WpfFact] public void Format_ExpressionBodiedMemberWithMultiLineBlock() { Test(@"using System; class TestClass { Func<int, int> Y() => delegate (int x) { return 9; }; $$ }", @"using System; class TestClass { Func<int, int> Y() => delegate(int x) { return 9; }$$ }"); } [WpfFact] public void Format_Statement() { Test(@"class C { void Method() { int i = 1; $$ } }", @"class C { void Method() { int i = 1 $$ } }"); } [WpfFact] public void Format_Using() { Test(@"using System.Linq; $$", @" using System . Linq $$"); } [WpfFact] public void Format_Using2() { Test(@"using System.Linq; $$", @" using System . Linq $$"); } [WpfFact] public void Format_Field() { Test(@"class C { int i = 1; $$ }", @"class C { int i = 1 $$ }"); } [WpfFact] public void Statement_Trivia() { Test(@"class C { void goo() { goo(); //comment $$ } }", @"class C { void goo() { goo()$$ //comment } }"); } [WpfFact] public void TrailingText_Negative() { Test(@"class C { event System.EventHandler e = null int i = 2; $$ }", @"class C { event System.EventHandler e = null$$ int i = 2; }"); } [WpfFact] public void CompletionSetUp() { Test(@"class Program { object goo(object o) { return goo(); $$ } }", @"class Program { object goo(object o) { return goo($$) } }", completionActive: true); } [WorkItem(530352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530352")] [WpfFact] public void EmbededStatement3() { Test(@"class Program { void Method() { foreach (var x in y) { $$ } } }", @"class Program { void Method() { foreach (var x in y$$) } }"); } [WorkItem(530716, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530716")] [WpfFact] public void DontAssertOnMultilineToken() { Test(@"interface I { void M(string s = @"""""" $$ }", @"interface I { void M(string s = @""""""$$ }"); } [WorkItem(530718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530718")] [WpfFact] public void AutomaticLineFormat() { Test(@"class C { public string P { set; get; } $$ }", @"class C { public string P {set;get;$$} }"); } [WpfFact] public void NotAfterExisitingSemicolon() { Test(@"class TestClass { private int i; $$ }", @"class TestClass { private int i;$$ }"); } [WpfFact] public void NotAfterCloseBraceInMethod() { Test(@"class TestClass { void Test() { } $$ }", @"class TestClass { void Test() { }$$ }"); } [WpfFact] public void NotAfterCloseBraceInStatement() { Test(@"class TestClass { void Test() { if (true) { } $$ } }", @"class TestClass { void Test() { if (true) { }$$ } }"); } [WpfFact] public void NotAfterAutoPropertyAccessor() { Test(@"class TestClass { public int A { get; set } $$ }", @"class TestClass { public int A { get; set$$ } }"); } [WpfFact] public void NotAfterAutoPropertyDeclaration() { Test(@"class TestClass { public int A { get; set; } $$ }", @"class TestClass { public int A { get; set; }$$ }"); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void DelegatedInEmptyBlock() { Test(@"class TestClass { void Method() { try { $$} } }", @"class TestClass { void Method() { try { $$} } }", assertNextHandlerInvoked: true); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void DelegatedInEmptyBlock2() { Test(@"class TestClass { void Method() { if (true) { $$} } }", @"class TestClass { void Method() { if (true) { $$} } }", assertNextHandlerInvoked: true); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void NotDelegatedOutsideEmptyBlock() { Test(@"class TestClass { void Method() { try { } $$ } }", @"class TestClass { void Method() { try { }$$ } }"); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void NotDelegatedAfterOpenBraceAndMissingCloseBrace() { Test(@"class TestClass { void Method() { try { $$ } }", @"class TestClass { void Method() { try {$$ } }"); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void NotDelegatedInNonEmptyBlock() { Test(@"class TestClass { void Method() { try { x } $$ } }", @"class TestClass { void Method() { try { x$$ } } }"); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void NotDelegatedAfterOpenBraceInAnonymousObjectCreationExpression() { Test(@"class TestClass { void Method() { var pet = new { }; $$ } }", @"class TestClass { void Method() { var pet = new { $$} } }"); } [WorkItem(150480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150480")] [WpfFact] public void NotDelegatedAfterOpenBraceObjectCreationExpression() { Test(@"class TestClass { void Method() { var pet = new List<int>(); $$ } }", @"class TestClass { void Method() { var pet = new List<int> { $$} } }"); } [WpfFact] public void TestMulitpleNamespace() { Test($@" namespace Bar2 {{ $$ }} namespace Bar {{ }}", $@" namespace B$$ar2$$ namespace Bar {{ }}"); } [WpfTheory] [InlineData("namespace")] [InlineData("class")] [InlineData("struct")] [InlineData("record")] [InlineData("enum")] [InlineData("interface")] public void TestEmptyBaseTypeDeclarationAndNamespace(string typeKeyword) { Test($@" public {typeKeyword} Bar {{ $$ }}", $@" pu$$blic {typeKeyword} $$Bar$$"); } [WpfTheory] [InlineData("class")] [InlineData("struct")] [InlineData("record")] [InlineData("enum")] [InlineData("interface")] public void TestMultipleBaseTypeDeclaration(string typeKeyword) { Test($@" public {typeKeyword} Bar2 {{ $$ }} public {typeKeyword} Bar {{ }}", $@" pub$$lic {typeKeyword} B$$ar2$$ public {typeKeyword} Bar {{ }}"); } [WpfFact] public void TestNestedTypeDeclaration() { Test(@" public class Bar1 { public class Bar2 { $$ } }", @" public class Bar1 { pu$$blic cla$$ss B$$ar2$$ }"); } [WpfFact] public void TestNestedNamespace() { Test(@" namespace Bar1 { namespace Bar2 { $$ } }", @" namespace Bar1 { namespa$$ce $$B$$ar2$$ }"); } [WpfTheory] [InlineData("namespace")] [InlineData("class")] [InlineData("struct")] [InlineData("record")] [InlineData("enum")] [InlineData("interface")] public void TestBaseTypeDeclarationAndNamespaceWithOpenBrace(string typeKeyword) { Test($@" public {typeKeyword} Bar {{ $$", $@" pub$$lic {typeKeyword} B$$ar {{$$"); } [WpfTheory] [InlineData("namespace")] [InlineData("class")] [InlineData("struct")] [InlineData("record")] [InlineData("enum")] [InlineData("interface")] public void TestValidTypeDeclarationAndNamespace(string typeKeyword) { Test($@"public {typeKeyword} Bar {{}} $$", $@"public {typeKeyword}$$ Ba$$r {{}}$$"); } [WpfFact] public void TestMethod() { Test(@" public class Bar { void Main() { $$ } }", @" public class Bar { v$$oid Ma$$in($$)$$ }"); } [WpfFact] public void TestConstructor() { Test(@" public class Bar { void Bar() { $$ } }", @" public class Bar { v$$oid Ba$$r($$)$$ }"); } [WpfFact] public void TestValidMethodInInterface() { Test(@" public interface Bar { void Main(); $$ }", @" public interface Bar { v$$oid Mai$$n($$)$$; }"); } [WpfFact] public void TestMissingSemicolonMethodInInterface() { Test(@" public interface Bar { void Main() $$ }", @" public interface Bar { v$$oid Mai$$n($$)$$ }"); } [WpfFact] public void TestValidLocalFunction() { Test(@" public class Bar { void Main() { void Local() $$ { } } }", @" public class Bar { void Main() { v$$oid Loc$$al($$)$$ { } } }"); } [WpfFact] public void TestLocalFunction() { Test(@" public class Bar { void Main() { void Local() { $$ } } }", @" public class Bar { void Main() { v$$oid Loca$$l($$)$$ } }"); } [WpfFact] public void TestIndexerAsLastElementInClass() { Test(@" public class Bar { public int this[int i] { $$ } }", @" public class Bar { p$$ublic in$$t thi$$s[in$$t i]$$ }"); } [WpfFact] public void TestIndexerNotAsLastElementInClass() { Test(@" public class Bar { public int this[int i] { $$ } void Main() {} }", @" public class Bar { p$$ublic in$$t thi$$s[in$$t i]$$ void Main() {} }"); } [WpfFact] public void TestValidIndexer() { Test(@" public class Bar { public int this[int i] $$ { } }", @" public class Bar { p$$ublic i$$nt thi$$s[in$$t i]$$ { } }"); } [WpfFact] public void TestGetAccessorOfProperty() { var initialMarkup = @" public class Bar { public int P { ge$$t } }"; var firstResult = @" public class Bar { public int P { get { $$ } } }"; var secondResult = @" public class Bar { public int P { get; $$ } }"; Test(firstResult, initialMarkup); Test(secondResult, firstResult); } [WpfFact] public void TestSetAccessorOfProperty() { var initialMarkup = @" public class Bar { public int P { set$$ } }"; var firstResult = @" public class Bar { public int P { set { $$ } } }"; var secondResult = @" public class Bar { public int P { set; $$ } }"; Test(firstResult, initialMarkup); Test(secondResult, firstResult); } [WpfFact] public void TestGetAccessorOfIndexer() { Test(@" public class Bar { public int this[int i] { get { $$ } } }", @" public class Bar { public int this[int i] { ge$$t } }"); } [WpfFact] public void TestValidGetAccessorOfIndexer() { Test(@" public class Bar { public int this[int i] { get { $$ } } }", @" public class Bar { public int this[int i] { get { $$ } } }"); } [WpfFact] public void TestNonEmptyGetAccessor() { Test(@" public Class Bar { public int P { get { if (true) $$ { return 1; } } } }", @" public Class Bar { public int P { get { i$$f ($$true$$)$$ { return 1; } } } }"); } [WpfFact] public void TestNonEmptySetAccessor() { Test(@" public Class Bar { public int P { get; set { if (true) $$ { } } } }", @" public Class Bar { public int P { get; set { i$$f (t$$rue)$$ { } } } }"); } [WpfFact] public void TestSetAccessorOfIndexer() { Test(@" public class Bar { public int this[int i] { get; set { $$ } } }", @" public class Bar { public int this[int i] { get; se$$t } }"); } [WpfFact] public void TestValidSetAccessorOfIndexer() { Test(@" public class Bar { public int this[int i] { get; set { $$ } } }", @" public class Bar { public int this[int i] { get; set { $$ } } }"); } [WpfFact] public void TestAddAccessorInEventDeclaration() { Test(@" using System; public class Bar { public event EventHandler e { add { $$ } remove } }", @" using System; public class Bar { public event EventHandler e { ad$$d remove } }"); } [WpfFact] public void TestValidAddAccessorInEventDeclaration() { Test(@" using System; public class Bar { public event EventHandler e { add { $$ } remove { } } }", @" using System; public class Bar { public event EventHandler e { add { $$ } remove { } } }"); } [WpfFact] public void TestRemoveAccessor() { Test(@" using System; public class Bar { public event EventHandler e { add remove { $$ } } }", @" using System; public class Bar { public event EventHandler e { add remo$$ve } }"); } [WpfFact] public void TestValidRemoveAccessor() { Test(@" using System; public class Bar { public event EventHandler e { add { } remove { $$ } } }", @" using System; public class Bar { public event EventHandler e { add { } remove { $$ } } }"); } [WpfFact] public void TestField() { var initialMarkup = @" public class Bar { p$$ublic i$$nt i$$ii$$ }"; var firstResult = @" public class Bar { public int iii { $$ } }"; var secondResult = @" public class Bar { public int iii; $$ }"; Test(firstResult, initialMarkup); Test(secondResult, firstResult); } [WpfFact] public void TestReadonlyField() { Test(@" public class Bar { public readonly int iii; $$ }", @" public class Bar { p$$ublic reado$$nly i$$nt i$$ii$$ }"); } [WpfFact] public void TestNonEmptyProperty() { Test(@" public class Bar { public int Foo { get { } $$ } }", @" public class Bar { public int Foo { $$get$$ { }$$ } }"); } [WpfFact] public void TestMulitpleFields() { Test(@" public class Bar { public int apple, banana; $$ }", @" public class Bar { p$$ublic i$$nt ap$$ple$$, ba$$nana;$$ }"); } [WpfFact] public void TestMultipleEvents() { Test(@" using System; public class Bar { public event EventHandler apple, banana; $$ }", @" using System; public class Bar { p$$ublic event EventHandler ap$$ple$$, ba$$nana$$;$$ }"); } [WpfFact] public void TestEvent() { var initialMarkup = @" using System; public class Bar { pu$$blic e$$vent EventHand$$ler c$$c$$ }"; var firstResult = @" using System; public class Bar { public event EventHandler cc { $$ } }"; var secondResult = @" using System; public class Bar { public event EventHandler cc; $$ }"; Test(firstResult, initialMarkup); Test(secondResult, firstResult); } [WpfFact] public void TestNonEmptyEvent() { Test(@" using System; public class Bar { public event EventHandler Foo { add { } $$ } }", @" using System; public class Bar { public event EventHandler Foo { $$add$$ {$$ }$$ } }"); } [WpfFact] public void TestObjectCreationExpressionWithParenthesis() { var initialMarkup = @" public class Bar { public void M() { var f = n$$ew F$$oo($$)$$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var firstResult = @" public class Bar { public void M() { var f = new Foo() { $$ }; } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var secondResult = @" public class Bar { public void M() { var f = new Foo(); $$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; Test(firstResult, initialMarkup); Test(secondResult, firstResult); } [WpfFact] public void TestObjectCreationExpressionWithNoParenthesis() { var initialMarkUp = @" public class Bar { public void M() { var f = n$$ew F$$oo$$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var firstResult = @" public class Bar { public void M() { var f = new Foo() { $$ }; } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var secondResult = @" public class Bar { public void M() { var f = new Foo(); $$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; Test(firstResult, initialMarkUp); Test(secondResult, firstResult); } [WpfFact] public void TestObjectCreationExpressionWithCorrectSemicolon() { var initialMarkUp = @" public class Bar { public void M() { var f = n$$ew F$$oo$$; } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var firstResult = @" public class Bar { public void M() { var f = new Foo() { $$ }; } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var secondResult = @" public class Bar { public void M() { var f = new Foo(); $$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; Test(firstResult, initialMarkUp); Test(secondResult, firstResult); } [WpfFact] public void TestObjectCreationExpressionUsedAsExpression() { var initialMarkUp = @" public class Bar { public void M() { N(ne$$w Fo$$o$$); } private void N(Foo f) { } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var firstResult = @" public class Bar { public void M() { N(new Foo() { $$ }); } private void N(Foo f) { } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var secondResult = @" public class Bar { public void M() { N(new Foo()); $$ } private void N(Foo f) { } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; Test(firstResult, initialMarkUp); Test(secondResult, firstResult); } [WpfFact] public void TestObjectCreationExpressionInUsingStatement() { var initialMarkup = @" public class Bar { public void M() { using(var a = n$$ew F$$oo($$)$$) } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var firstResult = @" public class Bar { public void M() { using(var a = new Foo() { $$ }) } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; var secondResult = @" public class Bar { public void M() { using(var a = new Foo()) $$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"; Test(firstResult, initialMarkup); Test(secondResult, firstResult); } [WpfFact] public void TestObjectCreationExpressionWithNonEmptyInitializer() { Test( @" public class Bar { public void M() { var a = new Foo() { HH = 1, PP = 2 }; $$ } } public class Foo { public int HH { get; set; } public int PP { get; set; } }", @" public class Bar { public void M() { var a = n$$ew Fo$$o($$) {$$ HH = 1$$, PP = 2 $$}; } } public class Foo { public int HH { get; set; } public int PP { get; set; } }"); } [WpfFact] public void TestIfStatementWithInnerStatement() { Test(@" public class Bar { public void Main(bool x) { if (x) { $$ } var z = 1; } }", @" public class Bar { public void Main(bool x) { i$$f$$ ($$x)$$ var z = 1; } }"); } [WpfFact] public void TestIfStatementWithFollowingElseClause() { Test(@" public class Bar { public void Main(bool x) { if (x) { $$ var z = 1; } else if (!x) } }", @" public class Bar { public void Main(bool x) { i$$f$$ ($$x)$$ var z = 1; else if (!x) } }"); } [WpfFact] public void TestIfStatementWithoutStatement() { Test(@" public class Bar { public void Main(bool x) { if (x) { $$ } } }", @" public class Bar { public void Main(bool x) { i$$f$$ ($$x)$$ } }"); } [WpfFact] public void TestNestIfStatementWithInnerStatement() { Test(@" public class Bar { public void Main(int x) { if (x == 1) if (x == 2) if (x == 3) if (x == 4) { $$ var a = 1000; } } }", @" public class Bar { public void Main(int x) { if (x == 1) if (x == 2) if (x == 3) i$$f ($$x =$$= 4)$$ var a = 1000; } }"); } [WpfFact] public void TestNestIfStatementWithoutInnerStatement() { Test(@" public class Bar { public void Main(int x) { if (x == 1) if (x == 2) if (x == 3) if (x == 4) { $$ } } }", @" public class Bar { public void Main(int x) { if (x == 1) if (x == 2) if (x == 3) i$$f ($$x =$$= 4)$$ } }"); } [WpfFact] public void TestNestedElseIfStatementWithInnerStatement() { Test(@" public class Bar { public void Fo(int i) { if (i == 1) { } else if (i == 2) if (i == 3) { $$ var i = 10; } else { } } }", @" public class Bar { public void Fo(int i) { if (i == 1) { } else if (i == 2) i$$f (i$$ == 3)$$ var i = 10; else { } } }"); } [WpfFact] public void TestNestIfElseStatementWithBlockWithInnerStatement() { Test(@" public class Bar { public void Main(int x) { if (x == 1) if (x == 2) if (x == 3) { if (x == 4) { $$ } var i = 10; } else { } } }", @" public class Bar { public void Main(int x) { if (x == 1) if (x == 2) if (x == 3) { i$$f ($$x =$$= 4)$$ var i = 10; } else { } } }"); } [WpfFact] public void TestEmptyDoStatement() { Test(@" public class Bar { public void Main() { do { $$ } } }", @" public class Bar { public void Main() { d$$o$$ } }"); } [WpfFact] public void TestDoStatementWithInnerStatement() { Test(@" public class Bar { public void Main() { do { $$ } var c = 10; } }", @" public class Bar { public void Main() { d$$o$$ var c = 10; } }"); } [WpfFact] public void TestDoStatementWithWhileClause() { Test(@" public class Bar { public void Main() { do { $$ var c = 10; } while (true); } }", @" public class Bar { public void Main() { d$$o$$ var c = 10; while (true); } }"); } [WpfFact] public void TestSingleElseStatement() { Test(@" public class Bar { public void Fo() { if (true) { } else { $$ } } }", @" public class Bar { public void Fo() { if (true) { } e$$lse$$ } }"); } [WpfFact] public void TestElseStatementWithInnerStatement() { Test(@" public class Bar { public void Fo() { if (true) { } else { $$ } var c = 10; } }", @" public class Bar { public void Fo() { if (true) { } e$$lse$$ var c = 10; } }"); } [WpfFact] public void TestElseIfStatement() { Test(@" public class Bar { public void Fo() { if (true) { } else if (false) { $$ } } }", @" public class Bar { public void Fo() { if (true) { } e$$lse i$$f ($$false)$$ } }"); } [WpfFact] public void TestElseIfInTheMiddleWithInnerStatement() { Test(@" public class Bar { public void Fo() { if (true) { } else if (false) { $$ var i = 10; } else { } } }", @" public class Bar { public void Fo() { if (true) { } e$$lse i$$f ($$false)$$ var i = 10; else { } } }"); } [WpfFact] public void TestElseClauseInNestedIfStatement() { Test(@" public class Bar { public void Fo(int i) { if (i == 1) { if (i == 2) var i = 10; else { $$ } var c = 100; } } }", @" public class Bar { public void Fo(int i) { if (i == 1) { if (i == 2) var i = 10; el$$se var c = 100; } } }"); } [WpfFact] public void TestForStatementWithoutStatement() { Test(@" public class Bar { public void Fo() { for (int i; i < 10; i++) { $$ } } }", @" public class Bar { public void Fo() { f$$or (i$$nt i; i < 10;$$ i++)$$ } }"); } [WpfFact] public void TestForStatementWithInnerStatement() { Test(@" public class Bar { public void Fo() { for (int i; i < 10; i++) { $$ } var c = 10; } }", @" public class Bar { public void Fo() { f$$or (i$$nt i; i < 10;$$ i++)$$ var c = 10; } }"); } [WpfFact] public void TestForEachStatementWithoutInnerStatement() { Test(@" public class Bar { public void Fo() { foreach (var x in """") { $$ } var c = 10; } }", @" public class Bar { public void Fo() { forea$$ch (var x $$in """")$$ var c = 10; } }"); } [WpfFact] public void TestLockStatementWithoutInnerStatement() { Test(@" public class Bar { object o = new object(); public void Fo() { lock (o) { $$ } } }", @" public class Bar { object o = new object(); public void Fo() { l$$ock$$(o)$$ } }"); } [WpfFact] public void TestLockStatementWithInnerStatement() { Test(@" public class Bar { object o = new object(); public void Fo() { lock (o) { $$ } var i = 10; } }", @" public class Bar { object o = new object(); public void Fo() { l$$ock$$(o)$$ var i = 10; } }"); } [WpfFact] public void TestUsingStatementWithoutInnerStatement() { Test(@" using System; public class Bar { public void Fo() { using (var d = new D()) { $$ } } } public class D : IDisposable { public void Dispose() {} }", @" using System; public class Bar { public void Fo() { usi$$ng (va$$r d = new D())$$ } } public class D : IDisposable { public void Dispose() {} }"); } [WpfFact] public void TestUsingStatementWithInnerStatement() { Test(@" using System; public class Bar { public void Fo() { using (var d = new D()) { $$ } var c = 10; } } public class D : IDisposable { public void Dispose() {} }", @" using System; public class Bar { public void Fo() { usi$$ng (va$$r d = new D())$$ var c = 10; } } public class D : IDisposable { public void Dispose() {} }"); } [WpfFact] public void TestUsingInLocalDeclarationStatement() { Test(@" using System; public class Bar { public void Fo() { using var d = new D(); $$ } } public class D : IDisposable { public void Dispose() {} }", @" using System; public class Bar { public void Fo() { usi$$ng v$$ar$$ d = new D() } } public class D : IDisposable { public void Dispose() {} }"); } [WpfFact] public void TestWhileStatementWithoutInnerStatement() { Test(@" public class Bar { public void Fo() { while (true) { $$ } } }", @" public class Bar { public void Fo() { wh$$ile (tr$$ue)$$ } }"); } [WpfFact] public void TestWhileStatementWithInnerStatement() { Test(@" public class Bar { public void Fo() { while (true) { $$ } var c = 10; } }", @" public class Bar { public void Fo() { wh$$ile (tr$$ue)$$ var c = 10; } }"); } [WpfFact] public void TestSwitchExpression1() { Test(@" public class Bar { public void Goo(int c) { var d = c switch { $$ } } }", @" public class Bar { public void Goo(int c) { var d = c swi$$tch$$ } }"); } [WpfFact] public void TestSwitchExpression2() { Test(@" public class Bar { public void Goo(int c) { var d = (c + 1) switch { $$ } } }", @" public class Bar { public void Goo(int c) { var d = (c + 1) swi$$tch$$ } }"); } [WpfFact] public void TestSwitchStatementWithOnlyOpenParenthesis() { // This test is to make sure {} will be added to the switch statement, // but our formatter now can't format the case when the CloseParenthesis token is missing. // If any future formatter improvement can handle this case, this test can be modified safely Test(@" public class bar { public void TT() { switch ( { $$ } } }", @" public class bar { public void TT() { swi$$tch ($$ } }"); } [WpfFact] public void TestSwitchStatement() { Test(@" public class bar { public void TT() { int i = 10; switch (i) { $$ } } }", @" public class bar { public void TT() { int i = 10; switc$$h ($$i)$$ } }"); } [WpfFact] public void TestValidSwitchStatement() { Test(@" public class bar { public void TT() { int i = 10; switch (i) $$ { } } }", @" public class bar { public void TT() { int i = 10; switc$$h ($$i)$$ { } } }"); } [WpfFact] public void TestValidTryStatement() { Test(@" public class bar { public void TT() { try $$ { } } }", @" public class bar { public void TT() { tr$$y$$ { } } }"); } [WpfFact] public void TestTryStatement() { Test(@" public class bar { public void TT() { try { $$ } } }", @" public class bar { public void TT() { tr$$y$$ } }"); } [WpfFact] public void TestValidCatchClause() { Test(@" public class Bar { public void TT() { try { } catch (System.Exception) $$ { } } }", @" public class Bar { public void TT() { try { } cat$$ch (Syste$$m.Exception)$$ { } } }"); } [WpfFact] public void TestCatchClauseWithException() { Test(@" public class Bar { public void TT() { try { } catch (System.Exception) { $$ } } }", @" public class Bar { public void TT() { try { } cat$$ch (Syste$$m.Exception)$$ } }"); } [WpfFact] public void TestSingleCatchClause() { Test(@" public class bar { public void TT() { try { } catch { $$ } } }", @" public class bar { public void TT() { try { } cat$$ch$$ } }"); } [WpfFact] public void TestCatchClauseWithWhenClause() { Test(@" public class bar { public void TT() { try { } catch (Exception) when (true) { $$ } } }", @" public class bar { public void TT() { try { } c$$atch (Ex$$ception) whe$$n (tru$$e)$$ } }"); } [WpfFact] public void TestFinallyCaluse() { Test(@" public class Bar { public void Bar2() { try { } catch (System.Exception) { } finally { $$ } } }", @" public class Bar { public void Bar2() { try { } catch (System.Exception) { } fin$$ally$$ } }"); } [WpfFact] public void TestValidFinallyCaluse() { Test(@" public class Bar { public void Bar2() { try { } catch (System.Exception) { } finally $$ { } } }", @" public class Bar { public void Bar2() { try { } catch (System.Exception) { } fin$$ally { } } }"); } protected override string Language => LanguageNames.CSharp; protected override Action CreateNextHandler(TestWorkspace workspace) => () => { }; internal override IChainedCommandHandler<AutomaticLineEnderCommandArgs> GetCommandHandler(TestWorkspace workspace) { return Assert.IsType<AutomaticLineEnderCommandHandler>( workspace.GetService<ICommandHandler>( ContentTypeNames.CSharpContentType, PredefinedCommandHandlerNames.AutomaticLineEnder)); } } }
1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/FormattingRangeHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Utilities { /// <summary> /// this help finding a range of tokens to format based on given ending token /// </summary> internal static class FormattingRangeHelper { public static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRange(SyntaxToken endToken, bool useDefaultRange = true) { Contract.ThrowIfTrue(endToken.Kind() == SyntaxKind.None); return FixupOpenBrace(FindAppropriateRangeWorker(endToken, useDefaultRange)); } private static ValueTuple<SyntaxToken, SyntaxToken>? FixupOpenBrace(ValueTuple<SyntaxToken, SyntaxToken>? tokenRange) { if (!tokenRange.HasValue) { return tokenRange; } // with a auto brace completion which will do auto formatting when a user types "{", it is quite common that we will automatically put a space // between "{" and "}". but user might blindly type without knowing that " " has automatically inserted for him. and ends up have two spaces. // for those cases, whenever we see previous token of the range is "{", we expand the range to include preceding "{" var currentToken = tokenRange.Value.Item1; var previousToken = currentToken.GetPreviousToken(); while (currentToken.Kind() != SyntaxKind.CloseBraceToken && previousToken.Kind() == SyntaxKind.OpenBraceToken) { var (_, closeBrace) = previousToken.Parent.GetBracePair(); if (closeBrace.Kind() == SyntaxKind.None || !AreTwoTokensOnSameLine(previousToken, closeBrace)) { return ValueTuple.Create(currentToken, tokenRange.Value.Item2); } currentToken = previousToken; previousToken = currentToken.GetPreviousToken(); } return ValueTuple.Create(currentToken, tokenRange.Value.Item2); } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeWorker(SyntaxToken endToken, bool useDefaultRange) { // special token that we know how to find proper starting token switch (endToken.Kind()) { case SyntaxKind.CloseBraceToken: { return FindAppropriateRangeForCloseBrace(endToken); } case SyntaxKind.SemicolonToken: { return FindAppropriateRangeForSemicolon(endToken); } case SyntaxKind.ColonToken: { return FindAppropriateRangeForColon(endToken); } default: { // default case if (!useDefaultRange) { return null; } // if given token is skipped token, don't bother to find appropriate // starting point if (endToken.Kind() == SyntaxKind.SkippedTokensTrivia) { return null; } var parent = endToken.Parent; if (parent == null) { // if there is no parent setup yet, nothing we can do here. return null; } // if we are called due to things in trivia or literals, don't bother // finding a starting token if (parent.Kind() is SyntaxKind.StringLiteralExpression or SyntaxKind.CharacterLiteralExpression) { return null; } // format whole node that containing the end token + its previous one // to do indentation return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } } } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForSemicolon(SyntaxToken endToken) { var parent = endToken.Parent; if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia) { return null; } if (parent is UsingDirectiveSyntax or DelegateDeclarationSyntax or FieldDeclarationSyntax or EventFieldDeclarationSyntax or MethodDeclarationSyntax or PropertyDeclarationSyntax or ConstructorDeclarationSyntax or DestructorDeclarationSyntax or OperatorDeclarationSyntax) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken()); } if (parent is AccessorDeclarationSyntax) { // if both accessors are on the same line, format the accessor list // { get; set; } if (GetEnclosingMember(endToken) is PropertyDeclarationSyntax propertyDeclaration && AreTwoTokensOnSameLine(propertyDeclaration.AccessorList!.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken)) { return ValueTuple.Create(propertyDeclaration.AccessorList.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken); } // otherwise, just format the accessor return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken()); } if (parent is StatementSyntax && !endToken.IsSemicolonInForStatement()) { var container = GetTopContainingNode(parent); if (container == null) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } if (IsSpecialContainingNode(container)) { return ValueTuple.Create(GetAppropriatePreviousToken(container.GetFirstToken()), container.GetLastToken()); } return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken()); } // don't do anything return null; } 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) { 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; } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForColon(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 (IsColonInSwitchLabel(endToken)) { return ValueTuple.Create(GetPreviousTokenIfNotFirstTokenInTree(parent.GetFirstToken()), parent.GetLastToken()); } return null; } private static SyntaxToken GetPreviousTokenIfNotFirstTokenInTree(SyntaxToken token) { var previousToken = token.GetPreviousToken(); return previousToken.Kind() == SyntaxKind.None ? token : previousToken; } public static bool AreTwoTokensOnSameLine(SyntaxToken token1, SyntaxToken token2) { if (token1 == token2) { return true; } var tree = token1.SyntaxTree; if (tree != null && tree.TryGetText(out var text)) { return text.AreOnSameLine(token1, token2); } return !CommonFormattingHelpers.GetTextBetween(token1, token2).ContainsLineBreak(); } private static SyntaxToken GetAppropriatePreviousToken(SyntaxToken startToken, bool canTokenBeFirstInABlock = false) { var previousToken = startToken.GetPreviousToken(); if (previousToken.Kind() == SyntaxKind.None) { // no previous token, return as it is return startToken; } if (AreTwoTokensOnSameLine(previousToken, startToken)) { // The previous token can be '{' of a block and type declaration // { int s = 0; if (canTokenBeFirstInABlock) { if (IsOpenBraceTokenOfABlockOrTypeOrNamespace(previousToken)) { return previousToken; } } // there is another token on same line. return startToken; } // start token is the first token on line // now check a special case where previous token belongs to a label. if (previousToken.IsLastTokenInLabelStatement()) { RoslynDebug.AssertNotNull(previousToken.Parent?.Parent); var labelNode = previousToken.Parent.Parent; return GetAppropriatePreviousToken(labelNode.GetFirstToken()); } return previousToken; } private static bool IsOpenBraceTokenOfABlockOrTypeOrNamespace(SyntaxToken previousToken) { return previousToken.IsKind(SyntaxKind.OpenBraceToken) && (previousToken.Parent.IsKind(SyntaxKind.Block) || previousToken.Parent is TypeDeclarationSyntax || previousToken.Parent is NamespaceDeclarationSyntax); } private static bool IsSpecialContainingNode(SyntaxNode node) { return node.Kind() is SyntaxKind.IfStatement or SyntaxKind.ElseClause or SyntaxKind.WhileStatement or SyntaxKind.ForStatement or SyntaxKind.ForEachStatement or SyntaxKind.ForEachVariableStatement or SyntaxKind.UsingStatement or SyntaxKind.DoStatement or SyntaxKind.TryStatement or SyntaxKind.CatchClause or SyntaxKind.FinallyClause or SyntaxKind.LabeledStatement or SyntaxKind.LockStatement or SyntaxKind.FixedStatement or SyntaxKind.UncheckedStatement or SyntaxKind.CheckedStatement or SyntaxKind.GetAccessorDeclaration or SyntaxKind.SetAccessorDeclaration or SyntaxKind.InitAccessorDeclaration or SyntaxKind.AddAccessorDeclaration or SyntaxKind.RemoveAccessorDeclaration; } private static SyntaxNode? GetTopContainingNode([DisallowNull] SyntaxNode? node) { RoslynDebug.AssertNotNull(node.Parent); node = node.Parent; if (!IsSpecialContainingNode(node)) { return node; } var lastSpecialContainingNode = node; node = node.Parent; while (node != null) { if (!IsSpecialContainingNode(node)) { return lastSpecialContainingNode; } lastSpecialContainingNode = node; node = node.Parent; } return null; } public static bool IsColonInSwitchLabel(SyntaxToken token) { return token.Kind() == SyntaxKind.ColonToken && token.Parent is SwitchLabelSyntax switchLabel && switchLabel.ColonToken == token; } public static bool InBetweenTwoMembers(SyntaxToken previousToken, SyntaxToken currentToken) { if (previousToken.Kind() is not SyntaxKind.SemicolonToken and not SyntaxKind.CloseBraceToken) { return false; } if (currentToken.Kind() == SyntaxKind.CloseBraceToken) { return false; } var previousMember = GetEnclosingMember(previousToken); var nextMember = GetEnclosingMember(currentToken); return previousMember != null && nextMember != null && previousMember != nextMember; } public static MemberDeclarationSyntax? GetEnclosingMember(SyntaxToken token) { RoslynDebug.AssertNotNull(token.Parent); if (token.Kind() == SyntaxKind.CloseBraceToken) { if (token.Parent.Kind() is SyntaxKind.Block or SyntaxKind.AccessorList) { return token.Parent.Parent as MemberDeclarationSyntax; } } return token.Parent.FirstAncestorOrSelf<MemberDeclarationSyntax>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Utilities { /// <summary> /// this help finding a range of tokens to format based on given ending token /// </summary> internal static class FormattingRangeHelper { public static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRange(SyntaxToken endToken, bool useDefaultRange = true) { Contract.ThrowIfTrue(endToken.Kind() == SyntaxKind.None); return FixupOpenBrace(FindAppropriateRangeWorker(endToken, useDefaultRange)); } private static ValueTuple<SyntaxToken, SyntaxToken>? FixupOpenBrace(ValueTuple<SyntaxToken, SyntaxToken>? tokenRange) { if (!tokenRange.HasValue) { return tokenRange; } // with a auto brace completion which will do auto formatting when a user types "{", it is quite common that we will automatically put a space // between "{" and "}". but user might blindly type without knowing that " " has automatically inserted for him. and ends up have two spaces. // for those cases, whenever we see previous token of the range is "{", we expand the range to include preceding "{" var currentToken = tokenRange.Value.Item1; var previousToken = currentToken.GetPreviousToken(); while (currentToken.Kind() != SyntaxKind.CloseBraceToken && previousToken.Kind() == SyntaxKind.OpenBraceToken) { var (_, closeBrace) = previousToken.Parent.GetBracePair(); if (closeBrace.Kind() == SyntaxKind.None || !AreTwoTokensOnSameLine(previousToken, closeBrace)) { return ValueTuple.Create(currentToken, tokenRange.Value.Item2); } currentToken = previousToken; previousToken = currentToken.GetPreviousToken(); } return ValueTuple.Create(currentToken, tokenRange.Value.Item2); } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeWorker(SyntaxToken endToken, bool useDefaultRange) { // special token that we know how to find proper starting token switch (endToken.Kind()) { case SyntaxKind.CloseBraceToken: { return FindAppropriateRangeForCloseBrace(endToken); } case SyntaxKind.SemicolonToken: { return FindAppropriateRangeForSemicolon(endToken); } case SyntaxKind.ColonToken: { return FindAppropriateRangeForColon(endToken); } default: { // default case if (!useDefaultRange) { return null; } // if given token is skipped token, don't bother to find appropriate // starting point if (endToken.Kind() == SyntaxKind.SkippedTokensTrivia) { return null; } var parent = endToken.Parent; if (parent == null) { // if there is no parent setup yet, nothing we can do here. return null; } // if we are called due to things in trivia or literals, don't bother // finding a starting token if (parent.Kind() is SyntaxKind.StringLiteralExpression or SyntaxKind.CharacterLiteralExpression) { return null; } // format whole node that containing the end token + its previous one // to do indentation return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } } } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForSemicolon(SyntaxToken endToken) { var parent = endToken.Parent; if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia) { return null; } if (parent is UsingDirectiveSyntax or DelegateDeclarationSyntax or FieldDeclarationSyntax or EventFieldDeclarationSyntax or MethodDeclarationSyntax or PropertyDeclarationSyntax or ConstructorDeclarationSyntax or DestructorDeclarationSyntax or OperatorDeclarationSyntax) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken()); } if (parent is AccessorDeclarationSyntax) { // if both accessors are on the same line, format the accessor list // { get; set; } if (GetEnclosingMember(endToken) is PropertyDeclarationSyntax propertyDeclaration && AreTwoTokensOnSameLine(propertyDeclaration.AccessorList!.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken)) { return ValueTuple.Create(propertyDeclaration.AccessorList.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken); } // otherwise, just format the accessor return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken()); } if (parent is StatementSyntax && !endToken.IsSemicolonInForStatement()) { var container = GetTopContainingNode(parent); if (container == null) { return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken()); } if (IsSpecialContainingNode(container)) { return ValueTuple.Create(GetAppropriatePreviousToken(container.GetFirstToken()), container.GetLastToken()); } return ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken(), canTokenBeFirstInABlock: true), parent.GetLastToken()); } // don't do anything return null; } 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; } private static ValueTuple<SyntaxToken, SyntaxToken>? FindAppropriateRangeForColon(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 (IsColonInSwitchLabel(endToken)) { return ValueTuple.Create(GetPreviousTokenIfNotFirstTokenInTree(parent.GetFirstToken()), parent.GetLastToken()); } return null; } private static SyntaxToken GetPreviousTokenIfNotFirstTokenInTree(SyntaxToken token) { var previousToken = token.GetPreviousToken(); return previousToken.Kind() == SyntaxKind.None ? token : previousToken; } public static bool AreTwoTokensOnSameLine(SyntaxToken token1, SyntaxToken token2) { if (token1 == token2) { return true; } var tree = token1.SyntaxTree; if (tree != null && tree.TryGetText(out var text)) { return text.AreOnSameLine(token1, token2); } return !CommonFormattingHelpers.GetTextBetween(token1, token2).ContainsLineBreak(); } private static SyntaxToken GetAppropriatePreviousToken(SyntaxToken startToken, bool canTokenBeFirstInABlock = false) { var previousToken = startToken.GetPreviousToken(); if (previousToken.Kind() == SyntaxKind.None) { // no previous token, return as it is return startToken; } if (AreTwoTokensOnSameLine(previousToken, startToken)) { // The previous token can be '{' of a block and type declaration // { int s = 0; if (canTokenBeFirstInABlock) { if (IsOpenBraceTokenOfABlockOrTypeOrNamespace(previousToken)) { return previousToken; } } // there is another token on same line. return startToken; } // start token is the first token on line // now check a special case where previous token belongs to a label. if (previousToken.IsLastTokenInLabelStatement()) { RoslynDebug.AssertNotNull(previousToken.Parent?.Parent); var labelNode = previousToken.Parent.Parent; return GetAppropriatePreviousToken(labelNode.GetFirstToken()); } return previousToken; } private static bool IsOpenBraceTokenOfABlockOrTypeOrNamespace(SyntaxToken previousToken) { return previousToken.IsKind(SyntaxKind.OpenBraceToken) && (previousToken.Parent.IsKind(SyntaxKind.Block) || previousToken.Parent is TypeDeclarationSyntax || previousToken.Parent is NamespaceDeclarationSyntax); } private static bool IsSpecialContainingNode(SyntaxNode node) { return node.Kind() is SyntaxKind.IfStatement or SyntaxKind.ElseClause or SyntaxKind.WhileStatement or SyntaxKind.ForStatement or SyntaxKind.ForEachStatement or SyntaxKind.ForEachVariableStatement or SyntaxKind.UsingStatement or SyntaxKind.DoStatement or SyntaxKind.TryStatement or SyntaxKind.CatchClause or SyntaxKind.FinallyClause or SyntaxKind.LabeledStatement or SyntaxKind.LockStatement or SyntaxKind.FixedStatement or SyntaxKind.UncheckedStatement or SyntaxKind.CheckedStatement or SyntaxKind.GetAccessorDeclaration or SyntaxKind.SetAccessorDeclaration or SyntaxKind.InitAccessorDeclaration or SyntaxKind.AddAccessorDeclaration or SyntaxKind.RemoveAccessorDeclaration; } private static SyntaxNode? GetTopContainingNode([DisallowNull] SyntaxNode? node) { RoslynDebug.AssertNotNull(node.Parent); node = node.Parent; if (!IsSpecialContainingNode(node)) { return node; } var lastSpecialContainingNode = node; node = node.Parent; while (node != null) { if (!IsSpecialContainingNode(node)) { return lastSpecialContainingNode; } lastSpecialContainingNode = node; node = node.Parent; } return null; } public static bool IsColonInSwitchLabel(SyntaxToken token) { return token.Kind() == SyntaxKind.ColonToken && token.Parent is SwitchLabelSyntax switchLabel && switchLabel.ColonToken == token; } public static bool InBetweenTwoMembers(SyntaxToken previousToken, SyntaxToken currentToken) { if (previousToken.Kind() is not SyntaxKind.SemicolonToken and not SyntaxKind.CloseBraceToken) { return false; } if (currentToken.Kind() == SyntaxKind.CloseBraceToken) { return false; } var previousMember = GetEnclosingMember(previousToken); var nextMember = GetEnclosingMember(currentToken); return previousMember != null && nextMember != null && previousMember != nextMember; } public static MemberDeclarationSyntax? GetEnclosingMember(SyntaxToken token) { RoslynDebug.AssertNotNull(token.Parent); if (token.Kind() == SyntaxKind.CloseBraceToken) { if (token.Parent.Kind() is SyntaxKind.Block or SyntaxKind.AccessorList) { return token.Parent.Parent as MemberDeclarationSyntax; } } return token.Parent.FirstAncestorOrSelf<MemberDeclarationSyntax>(); } } }
1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Compilers/Core/Portable/CodeGen/EmitState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeGen { internal partial class ILBuilder { /// <summary> /// Abstract Execution state. /// If we know something interesting about IL stream we put it here. /// </summary> private struct EmitState { private int _maxStack; private int _curStack; private int _instructionsEmitted; internal int InstructionsEmitted { get { return _instructionsEmitted; } } internal void InstructionAdded() { _instructionsEmitted += 1; } /// <summary> /// Eval stack's high watermark. /// </summary> internal int MaxStack { get { return _maxStack; } private set { Debug.Assert(value >= 0 && value <= ushort.MaxValue); _maxStack = value; } } /// <summary> /// Current evaluation stack depth. /// </summary> internal int CurStack { get { return _curStack; } private set { Debug.Assert(value >= 0 && value <= ushort.MaxValue); _curStack = value; } } //TODO: for debugging we could also record what we have in the stack (I, F, O, &, ...) /// <summary> /// Record effects of that currently emitted instruction on the eval stack. /// </summary> internal void AdjustStack(int count) { CurStack += count; MaxStack = Math.Max(MaxStack, CurStack); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeGen { internal partial class ILBuilder { /// <summary> /// Abstract Execution state. /// If we know something interesting about IL stream we put it here. /// </summary> private struct EmitState { private int _maxStack; private int _curStack; private int _instructionsEmitted; internal int InstructionsEmitted { get { return _instructionsEmitted; } } internal void InstructionAdded() { _instructionsEmitted += 1; } /// <summary> /// Eval stack's high watermark. /// </summary> internal int MaxStack { get { return _maxStack; } private set { Debug.Assert(value >= 0 && value <= ushort.MaxValue); _maxStack = value; } } /// <summary> /// Current evaluation stack depth. /// </summary> internal int CurStack { get { return _curStack; } private set { Debug.Assert(value >= 0 && value <= ushort.MaxValue); _curStack = value; } } //TODO: for debugging we could also record what we have in the stack (I, F, O, &, ...) /// <summary> /// Record effects of that currently emitted instruction on the eval stack. /// </summary> internal void AdjustStack(int count) { CurStack += count; MaxStack = Math.Max(MaxStack, CurStack); } } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/EditorFeatures/Core.Cocoa/Snippets/SnippetFunctions/AbstractSnippetFunctionSimpleTypeName.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions { internal abstract class AbstractSnippetFunctionSimpleTypeName : AbstractSnippetFunction { private readonly string _fieldName; private readonly string _fullyQualifiedName; public AbstractSnippetFunctionSimpleTypeName(AbstractSnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName, string fullyQualifiedName) : base(snippetExpansionClient, subjectBuffer) { _fieldName = fieldName; _fullyQualifiedName = fullyQualifiedName; } protected abstract bool TryGetSimplifiedTypeName(Document documentWithFullyQualifiedTypeName, TextSpan updatedTextSpan, CancellationToken cancellationToken, out string simplifiedTypeName); protected override void GetDefaultValue(CancellationToken cancellationToken, out string value, out bool hasCurrentValue) { value = _fullyQualifiedName; hasCurrentValue = true; if (!TryGetDocument(out var document)) { throw new System.Exception(); } if (!TryGetDocumentWithFullyQualifiedTypeName(document, out var updatedTextSpan, out var documentWithFullyQualifiedTypeName)) { throw new System.Exception(); } if (!TryGetSimplifiedTypeName(documentWithFullyQualifiedTypeName, updatedTextSpan, cancellationToken, out var simplifiedName)) { throw new System.Exception(); } value = simplifiedName; hasCurrentValue = true; } private bool TryGetDocumentWithFullyQualifiedTypeName(Document document, out TextSpan updatedTextSpan, [NotNullWhen(returnValue: true)] out Document? documentWithFullyQualifiedTypeName) { documentWithFullyQualifiedTypeName = null; updatedTextSpan = default; Contract.ThrowIfNull(_snippetExpansionClient.ExpansionSession); var surfaceBufferFieldSpan = _snippetExpansionClient.ExpansionSession.GetFieldSpan(_fieldName); if (!_snippetExpansionClient.TryGetSubjectBufferSpan(surfaceBufferFieldSpan, out var subjectBufferFieldSpan)) { return false; } var originalTextSpan = new TextSpan(subjectBufferFieldSpan.Start, subjectBufferFieldSpan.Length); updatedTextSpan = new TextSpan(subjectBufferFieldSpan.Start, _fullyQualifiedName.Length); var textChange = new TextChange(originalTextSpan, _fullyQualifiedName); var newText = document.GetTextSynchronously(CancellationToken.None).WithChanges(textChange); documentWithFullyQualifiedTypeName = document.WithText(newText); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions { internal abstract class AbstractSnippetFunctionSimpleTypeName : AbstractSnippetFunction { private readonly string _fieldName; private readonly string _fullyQualifiedName; public AbstractSnippetFunctionSimpleTypeName(AbstractSnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName, string fullyQualifiedName) : base(snippetExpansionClient, subjectBuffer) { _fieldName = fieldName; _fullyQualifiedName = fullyQualifiedName; } protected abstract bool TryGetSimplifiedTypeName(Document documentWithFullyQualifiedTypeName, TextSpan updatedTextSpan, CancellationToken cancellationToken, out string simplifiedTypeName); protected override void GetDefaultValue(CancellationToken cancellationToken, out string value, out bool hasCurrentValue) { value = _fullyQualifiedName; hasCurrentValue = true; if (!TryGetDocument(out var document)) { throw new System.Exception(); } if (!TryGetDocumentWithFullyQualifiedTypeName(document, out var updatedTextSpan, out var documentWithFullyQualifiedTypeName)) { throw new System.Exception(); } if (!TryGetSimplifiedTypeName(documentWithFullyQualifiedTypeName, updatedTextSpan, cancellationToken, out var simplifiedName)) { throw new System.Exception(); } value = simplifiedName; hasCurrentValue = true; } private bool TryGetDocumentWithFullyQualifiedTypeName(Document document, out TextSpan updatedTextSpan, [NotNullWhen(returnValue: true)] out Document? documentWithFullyQualifiedTypeName) { documentWithFullyQualifiedTypeName = null; updatedTextSpan = default; Contract.ThrowIfNull(_snippetExpansionClient.ExpansionSession); var surfaceBufferFieldSpan = _snippetExpansionClient.ExpansionSession.GetFieldSpan(_fieldName); if (!_snippetExpansionClient.TryGetSubjectBufferSpan(surfaceBufferFieldSpan, out var subjectBufferFieldSpan)) { return false; } var originalTextSpan = new TextSpan(subjectBufferFieldSpan.Start, subjectBufferFieldSpan.Length); updatedTextSpan = new TextSpan(subjectBufferFieldSpan.Start, _fullyQualifiedName.Length); var textChange = new TextChange(originalTextSpan, _fullyQualifiedName); var newText = document.GetTextSynchronously(CancellationToken.None).WithChanges(textChange); documentWithFullyQualifiedTypeName = document.WithText(newText); return true; } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Compilers/Core/Rebuild/CompilationFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Rebuild { public abstract class CompilationFactory { public string AssemblyFileName { get; } public CompilationOptionsReader OptionsReader { get; } public ParseOptions ParseOptions => CommonParseOptions; public CompilationOptions CompilationOptions => CommonCompilationOptions; protected abstract ParseOptions CommonParseOptions { get; } protected abstract CompilationOptions CommonCompilationOptions { get; } protected CompilationFactory(string assemblyFileName, CompilationOptionsReader optionsReader) { AssemblyFileName = assemblyFileName; OptionsReader = optionsReader; } public static CompilationFactory Create(string assemblyFileName, CompilationOptionsReader optionsReader) => optionsReader.GetLanguageName() switch { LanguageNames.CSharp => CSharpCompilationFactory.Create(assemblyFileName, optionsReader), LanguageNames.VisualBasic => VisualBasicCompilationFactory.Create(assemblyFileName, optionsReader), var language => throw new InvalidDataException($"{assemblyFileName} has unsupported language {language}") }; public abstract SyntaxTree CreateSyntaxTree(string filePath, SourceText sourceText); public Compilation CreateCompilation(IRebuildArtifactResolver resolver) { var tuple = OptionsReader.ResolveArtifacts(resolver, CreateSyntaxTree); return CreateCompilation(tuple.SyntaxTrees, tuple.MetadataReferences); } public abstract Compilation CreateCompilation( ImmutableArray<SyntaxTree> syntaxTrees, ImmutableArray<MetadataReference> metadataReferences); public EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, IRebuildArtifactResolver rebuildArtifactResolver, CancellationToken cancellationToken) => Emit( rebuildPeStream, rebuildPdbStream, CreateCompilation(rebuildArtifactResolver), cancellationToken); public EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, ImmutableArray<SyntaxTree> syntaxTrees, ImmutableArray<MetadataReference> metadataReferences, CancellationToken cancellationToken) => Emit( rebuildPeStream, rebuildPdbStream, CreateCompilation(syntaxTrees, metadataReferences), cancellationToken); public EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, Compilation rebuildCompilation, CancellationToken cancellationToken) { var embeddedTexts = rebuildCompilation.SyntaxTrees .Select(st => (path: st.FilePath, text: st.GetText())) .Where(pair => pair.text.CanBeEmbedded) .Select(pair => EmbeddedText.FromSource(pair.path, pair.text)) .ToImmutableArray(); return Emit( rebuildPeStream, rebuildPdbStream, rebuildCompilation, embeddedTexts, cancellationToken); } public unsafe EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, Compilation rebuildCompilation, ImmutableArray<EmbeddedText> embeddedTexts, CancellationToken cancellationToken) { var peHeader = OptionsReader.PeReader.PEHeaders.PEHeader!; var win32Resources = OptionsReader.PeReader.GetSectionData(peHeader.ResourceTableDirectory.RelativeVirtualAddress); using var win32ResourceStream = win32Resources.Pointer != null ? new UnmanagedMemoryStream(win32Resources.Pointer, win32Resources.Length) : null; var sourceLink = OptionsReader.GetSourceLinkUTF8(); var debugEntryPoint = getDebugEntryPoint(); string? pdbFilePath; DebugInformationFormat debugInformationFormat; if (OptionsReader.HasEmbeddedPdb) { if (rebuildPdbStream is object) { throw new ArgumentException(RebuildResources.PDB_stream_must_be_null_because_the_compilation_has_an_embedded_PDB, nameof(rebuildPdbStream)); } debugInformationFormat = DebugInformationFormat.Embedded; pdbFilePath = null; } else { if (rebuildPdbStream is null) { throw new ArgumentException(RebuildResources.A_non_null_PDB_stream_must_be_provided_because_the_compilation_does_not_have_an_embedded_PDB, nameof(rebuildPdbStream)); } debugInformationFormat = DebugInformationFormat.PortablePdb; var codeViewEntry = OptionsReader.PeReader.ReadDebugDirectory().Single(entry => entry.Type == DebugDirectoryEntryType.CodeView); var codeView = OptionsReader.PeReader.ReadCodeViewDebugDirectoryData(codeViewEntry); pdbFilePath = codeView.Path ?? throw new InvalidOperationException(RebuildResources.Could_not_get_PDB_file_path); } var rebuildData = new RebuildData( OptionsReader.GetMetadataCompilationOptionsBlobReader(), getNonSourceFileDocumentNames(OptionsReader.PdbReader, OptionsReader.GetSourceFileCount())); var emitResult = rebuildCompilation.Emit( peStream: rebuildPeStream, pdbStream: rebuildPdbStream, xmlDocumentationStream: null, win32Resources: win32ResourceStream, manifestResources: OptionsReader.GetManifestResources(), options: new EmitOptions( debugInformationFormat: debugInformationFormat, pdbFilePath: pdbFilePath, highEntropyVirtualAddressSpace: (peHeader.DllCharacteristics & DllCharacteristics.HighEntropyVirtualAddressSpace) != 0, subsystemVersion: SubsystemVersion.Create(peHeader.MajorSubsystemVersion, peHeader.MinorSubsystemVersion)), debugEntryPoint: debugEntryPoint, metadataPEStream: null, rebuildData: rebuildData, sourceLinkStream: sourceLink != null ? new MemoryStream(sourceLink) : null, embeddedTexts: embeddedTexts, cancellationToken: cancellationToken); return emitResult; static ImmutableArray<string> getNonSourceFileDocumentNames(MetadataReader pdbReader, int sourceFileCount) { var count = pdbReader.Documents.Count - sourceFileCount; var builder = ArrayBuilder<string>.GetInstance(count); foreach (var documentHandle in pdbReader.Documents.Skip(sourceFileCount)) { var document = pdbReader.GetDocument(documentHandle); var name = pdbReader.GetString(document.Name); builder.Add(name); } return builder.ToImmutableAndFree(); } IMethodSymbol? getDebugEntryPoint() { if (OptionsReader.GetMainMethodInfo() is (string mainTypeName, string mainMethodName)) { var typeSymbol = rebuildCompilation.GetTypeByMetadataName(mainTypeName); if (typeSymbol is object) { var methodSymbols = typeSymbol .GetMembers(mainMethodName) .OfType<IMethodSymbol>(); return methodSymbols.FirstOrDefault(); } } return null; } } protected static (OptimizationLevel OptimizationLevel, bool DebugPlus) GetOptimizationLevel(string? value) { if (value is null) { return OptimizationLevelFacts.DefaultValues; } if (!OptimizationLevelFacts.TryParsePdbSerializedString(value, out OptimizationLevel optimizationLevel, out bool debugPlus)) { throw new InvalidOperationException(); } return (optimizationLevel, debugPlus); } protected static Platform GetPlatform(string? platform) => platform is null ? Platform.AnyCpu : (Platform)Enum.Parse(typeof(Platform), platform); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Rebuild { public abstract class CompilationFactory { public string AssemblyFileName { get; } public CompilationOptionsReader OptionsReader { get; } public ParseOptions ParseOptions => CommonParseOptions; public CompilationOptions CompilationOptions => CommonCompilationOptions; protected abstract ParseOptions CommonParseOptions { get; } protected abstract CompilationOptions CommonCompilationOptions { get; } protected CompilationFactory(string assemblyFileName, CompilationOptionsReader optionsReader) { AssemblyFileName = assemblyFileName; OptionsReader = optionsReader; } public static CompilationFactory Create(string assemblyFileName, CompilationOptionsReader optionsReader) => optionsReader.GetLanguageName() switch { LanguageNames.CSharp => CSharpCompilationFactory.Create(assemblyFileName, optionsReader), LanguageNames.VisualBasic => VisualBasicCompilationFactory.Create(assemblyFileName, optionsReader), var language => throw new InvalidDataException($"{assemblyFileName} has unsupported language {language}") }; public abstract SyntaxTree CreateSyntaxTree(string filePath, SourceText sourceText); public Compilation CreateCompilation(IRebuildArtifactResolver resolver) { var tuple = OptionsReader.ResolveArtifacts(resolver, CreateSyntaxTree); return CreateCompilation(tuple.SyntaxTrees, tuple.MetadataReferences); } public abstract Compilation CreateCompilation( ImmutableArray<SyntaxTree> syntaxTrees, ImmutableArray<MetadataReference> metadataReferences); public EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, IRebuildArtifactResolver rebuildArtifactResolver, CancellationToken cancellationToken) => Emit( rebuildPeStream, rebuildPdbStream, CreateCompilation(rebuildArtifactResolver), cancellationToken); public EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, ImmutableArray<SyntaxTree> syntaxTrees, ImmutableArray<MetadataReference> metadataReferences, CancellationToken cancellationToken) => Emit( rebuildPeStream, rebuildPdbStream, CreateCompilation(syntaxTrees, metadataReferences), cancellationToken); public EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, Compilation rebuildCompilation, CancellationToken cancellationToken) { var embeddedTexts = rebuildCompilation.SyntaxTrees .Select(st => (path: st.FilePath, text: st.GetText())) .Where(pair => pair.text.CanBeEmbedded) .Select(pair => EmbeddedText.FromSource(pair.path, pair.text)) .ToImmutableArray(); return Emit( rebuildPeStream, rebuildPdbStream, rebuildCompilation, embeddedTexts, cancellationToken); } public unsafe EmitResult Emit( Stream rebuildPeStream, Stream? rebuildPdbStream, Compilation rebuildCompilation, ImmutableArray<EmbeddedText> embeddedTexts, CancellationToken cancellationToken) { var peHeader = OptionsReader.PeReader.PEHeaders.PEHeader!; var win32Resources = OptionsReader.PeReader.GetSectionData(peHeader.ResourceTableDirectory.RelativeVirtualAddress); using var win32ResourceStream = win32Resources.Pointer != null ? new UnmanagedMemoryStream(win32Resources.Pointer, win32Resources.Length) : null; var sourceLink = OptionsReader.GetSourceLinkUTF8(); var debugEntryPoint = getDebugEntryPoint(); string? pdbFilePath; DebugInformationFormat debugInformationFormat; if (OptionsReader.HasEmbeddedPdb) { if (rebuildPdbStream is object) { throw new ArgumentException(RebuildResources.PDB_stream_must_be_null_because_the_compilation_has_an_embedded_PDB, nameof(rebuildPdbStream)); } debugInformationFormat = DebugInformationFormat.Embedded; pdbFilePath = null; } else { if (rebuildPdbStream is null) { throw new ArgumentException(RebuildResources.A_non_null_PDB_stream_must_be_provided_because_the_compilation_does_not_have_an_embedded_PDB, nameof(rebuildPdbStream)); } debugInformationFormat = DebugInformationFormat.PortablePdb; var codeViewEntry = OptionsReader.PeReader.ReadDebugDirectory().Single(entry => entry.Type == DebugDirectoryEntryType.CodeView); var codeView = OptionsReader.PeReader.ReadCodeViewDebugDirectoryData(codeViewEntry); pdbFilePath = codeView.Path ?? throw new InvalidOperationException(RebuildResources.Could_not_get_PDB_file_path); } var rebuildData = new RebuildData( OptionsReader.GetMetadataCompilationOptionsBlobReader(), getNonSourceFileDocumentNames(OptionsReader.PdbReader, OptionsReader.GetSourceFileCount())); var emitResult = rebuildCompilation.Emit( peStream: rebuildPeStream, pdbStream: rebuildPdbStream, xmlDocumentationStream: null, win32Resources: win32ResourceStream, manifestResources: OptionsReader.GetManifestResources(), options: new EmitOptions( debugInformationFormat: debugInformationFormat, pdbFilePath: pdbFilePath, highEntropyVirtualAddressSpace: (peHeader.DllCharacteristics & DllCharacteristics.HighEntropyVirtualAddressSpace) != 0, subsystemVersion: SubsystemVersion.Create(peHeader.MajorSubsystemVersion, peHeader.MinorSubsystemVersion)), debugEntryPoint: debugEntryPoint, metadataPEStream: null, rebuildData: rebuildData, sourceLinkStream: sourceLink != null ? new MemoryStream(sourceLink) : null, embeddedTexts: embeddedTexts, cancellationToken: cancellationToken); return emitResult; static ImmutableArray<string> getNonSourceFileDocumentNames(MetadataReader pdbReader, int sourceFileCount) { var count = pdbReader.Documents.Count - sourceFileCount; var builder = ArrayBuilder<string>.GetInstance(count); foreach (var documentHandle in pdbReader.Documents.Skip(sourceFileCount)) { var document = pdbReader.GetDocument(documentHandle); var name = pdbReader.GetString(document.Name); builder.Add(name); } return builder.ToImmutableAndFree(); } IMethodSymbol? getDebugEntryPoint() { if (OptionsReader.GetMainMethodInfo() is (string mainTypeName, string mainMethodName)) { var typeSymbol = rebuildCompilation.GetTypeByMetadataName(mainTypeName); if (typeSymbol is object) { var methodSymbols = typeSymbol .GetMembers(mainMethodName) .OfType<IMethodSymbol>(); return methodSymbols.FirstOrDefault(); } } return null; } } protected static (OptimizationLevel OptimizationLevel, bool DebugPlus) GetOptimizationLevel(string? value) { if (value is null) { return OptimizationLevelFacts.DefaultValues; } if (!OptimizationLevelFacts.TryParsePdbSerializedString(value, out OptimizationLevel optimizationLevel, out bool debugPlus)) { throw new InvalidOperationException(); } return (optimizationLevel, debugPlus); } protected static Platform GetPlatform(string? platform) => platform is null ? Platform.AnyCpu : (Platform)Enum.Parse(typeof(Platform), platform); } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/EditorFeatures/Test/EditAndContinue/EditAndContinueDiagnosticDescriptorsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public class EditAndContinueDiagnosticDescriptorsTests { [Fact] public void GetDescriptor() { var d = EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.ActiveStatementUpdate); Assert.Equal("ENC0001", d.Id); Assert.Equal(DiagnosticCategory.EditAndContinue, d.Category); Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable", EnforceOnBuild.Never.ToCustomTag() }, d.CustomTags); Assert.Equal("", d.Description); Assert.Equal("", d.HelpLinkUri); Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.RudeEdit), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title); Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.Updating_an_active_statement_requires_restarting_the_application), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat); Assert.Equal("ENC0087", EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.ComplexQueryExpression).Id); d = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); Assert.Equal("ENC1001", d.Id); Assert.Equal(DiagnosticCategory.EditAndContinue, d.Category); Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable", EnforceOnBuild.Never.ToCustomTag() }, d.CustomTags); Assert.Equal("", d.Description); Assert.Equal("", d.HelpLinkUri); Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinue), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title); Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.ErrorReadingFile), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat); d = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(ManagedEditAndContinueAvailabilityStatus.Optimized); Assert.Equal("ENC2012", d.Id); Assert.Equal(DiagnosticCategory.EditAndContinue, d.Category); Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable", EnforceOnBuild.Never.ToCustomTag() }, d.CustomTags); Assert.Equal("", d.Description); Assert.Equal("", d.HelpLinkUri); Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinue), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title); Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinueDisallowedByProject), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat); } [Fact] public void GetDescriptors() { var descriptors = EditAndContinueDiagnosticDescriptors.GetDescriptors(); Assert.NotEmpty(descriptors); Assert.True(descriptors.All(d => d != null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public class EditAndContinueDiagnosticDescriptorsTests { [Fact] public void GetDescriptor() { var d = EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.ActiveStatementUpdate); Assert.Equal("ENC0001", d.Id); Assert.Equal(DiagnosticCategory.EditAndContinue, d.Category); Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable", EnforceOnBuild.Never.ToCustomTag() }, d.CustomTags); Assert.Equal("", d.Description); Assert.Equal("", d.HelpLinkUri); Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.RudeEdit), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title); Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.Updating_an_active_statement_requires_restarting_the_application), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat); Assert.Equal("ENC0087", EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.ComplexQueryExpression).Id); d = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); Assert.Equal("ENC1001", d.Id); Assert.Equal(DiagnosticCategory.EditAndContinue, d.Category); Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable", EnforceOnBuild.Never.ToCustomTag() }, d.CustomTags); Assert.Equal("", d.Description); Assert.Equal("", d.HelpLinkUri); Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinue), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title); Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.ErrorReadingFile), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat); d = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(ManagedEditAndContinueAvailabilityStatus.Optimized); Assert.Equal("ENC2012", d.Id); Assert.Equal(DiagnosticCategory.EditAndContinue, d.Category); Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable", EnforceOnBuild.Never.ToCustomTag() }, d.CustomTags); Assert.Equal("", d.Description); Assert.Equal("", d.HelpLinkUri); Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinue), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title); Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinueDisallowedByProject), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat); } [Fact] public void GetDescriptors() { var descriptors = EditAndContinueDiagnosticDescriptors.GetDescriptors(); Assert.NotEmpty(descriptors); Assert.True(descriptors.All(d => d != null)); } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/ExpressionEvaluator/Core/Source/FunctionResolver/MetadataResolver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal delegate void OnFunctionResolvedDelegate<TModule, TRequest>(TModule module, TRequest request, int token, int version, int ilOffset); internal sealed class MetadataResolver<TProcess, TModule, TRequest> where TProcess : class where TModule : class where TRequest : class { private readonly TModule _module; private readonly MetadataReader _reader; private readonly StringComparer _stringComparer; // for comparing strings private readonly bool _ignoreCase; // for comparing strings to strings represented with StringHandles private readonly OnFunctionResolvedDelegate<TModule, TRequest> _onFunctionResolved; internal MetadataResolver( TModule module, MetadataReader reader, bool ignoreCase, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { _module = module; _reader = reader; _stringComparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; _ignoreCase = ignoreCase; _onFunctionResolved = onFunctionResolved; } internal void Resolve(TRequest request, RequestSignature signature) { QualifiedName qualifiedTypeName; ImmutableArray<string> memberTypeParameters; GetNameAndTypeParameters(signature.MemberName, out qualifiedTypeName, out memberTypeParameters); var typeName = qualifiedTypeName.Qualifier; var memberName = qualifiedTypeName.Name; var memberParameters = signature.Parameters; var allTypeParameters = GetAllGenericTypeParameters(typeName); foreach (var typeHandle in _reader.TypeDefinitions) { var typeDef = _reader.GetTypeDefinition(typeHandle); int containingArity = CompareToTypeDefinition(typeDef, typeName); if (containingArity < 0) { continue; } // Visit methods. foreach (var methodHandle in typeDef.GetMethods()) { var methodDef = _reader.GetMethodDefinition(methodHandle); if (!IsResolvableMethod(methodDef)) { continue; } if (MatchesMethod(typeDef, methodDef, memberName, allTypeParameters, containingArity, memberTypeParameters, memberParameters)) { OnFunctionResolved(request, methodHandle); } } if (memberTypeParameters.IsEmpty) { // Visit properties. foreach (var propertyHandle in typeDef.GetProperties()) { var propertyDef = _reader.GetPropertyDefinition(propertyHandle); var accessors = propertyDef.GetAccessors(); if (MatchesPropertyOrEvent(propertyDef.Name, accessors.Getter, memberName, allTypeParameters, containingArity, memberParameters)) { OnAccessorResolved(request, accessors.Getter); OnAccessorResolved(request, accessors.Setter); } } // Visit events. foreach (var eventHandle in typeDef.GetEvents()) { var eventDef = _reader.GetEventDefinition(eventHandle); var accessors = eventDef.GetAccessors(); if (MatchesPropertyOrEvent(eventDef.Name, accessors.Adder, memberName, allTypeParameters, containingArity, memberParameters)) { OnAccessorResolved(request, accessors.Adder); OnAccessorResolved(request, accessors.Remover); } } } } } // If the signature matches the TypeDefinition, including some or all containing // types and namespaces, returns a non-negative value indicating the arity of the // containing types that were not specified in the signature; otherwise returns -1. // For instance, "C<T>.D" will return 1 matching against metadata type N.M.A<T>.B.C<U>.D, // where N.M is a namespace and A<T>, B, C<U>, D are nested types. The value 1 // is the arity of the containing types A<T>.B that were missing from the signature. // "C<T>.D" will not match C<T> or C<T>.D.E since the match must include the entire // signature, from nested TypeDefinition, out. private int CompareToTypeDefinition(TypeDefinition typeDef, Name signature) { if (signature == null) { return typeDef.GetGenericParameters().Count; } QualifiedName qualifiedName; ImmutableArray<string> typeParameters; GetNameAndTypeParameters(signature, out qualifiedName, out typeParameters); if (!MatchesTypeName(typeDef, qualifiedName.Name)) { return -1; } var declaringTypeHandle = typeDef.GetDeclaringType(); var declaringType = declaringTypeHandle.IsNil ? default : _reader.GetTypeDefinition(declaringTypeHandle); int declaringTypeParameterCount = declaringTypeHandle.IsNil ? 0 : declaringType.GetGenericParameters().Count; if (!MatchesTypeParameterCount(typeParameters, typeDef.GetGenericParameters(), declaringTypeParameterCount)) { return -1; } var qualifier = qualifiedName.Qualifier; if (declaringTypeHandle.IsNil) { // Compare namespace. return MatchesNamespace(typeDef, qualifier) ? 0 : -1; } else { // Compare declaring type. return CompareToTypeDefinition(declaringType, qualifier); } } private bool MatchesNamespace(TypeDefinition typeDef, Name signature) { if (signature == null) { return true; } var namespaceName = _reader.GetString(typeDef.Namespace); if (string.IsNullOrEmpty(namespaceName)) { return false; } var parts = namespaceName.Split('.'); for (int index = parts.Length - 1; index >= 0; index--) { if (signature == null) { return true; } var qualifiedName = signature as QualifiedName; if (qualifiedName == null) { return false; } var part = parts[index]; if (!_stringComparer.Equals(qualifiedName.Name, part)) { return false; } signature = qualifiedName.Qualifier; } return signature == null; } private bool MatchesTypeName(TypeDefinition typeDef, string name) { var typeName = RemoveAritySeparatorIfAny(_reader.GetString(typeDef.Name)); return _stringComparer.Equals(typeName, name); } private bool MatchesMethod( TypeDefinition typeDef, MethodDefinition methodDef, string methodName, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<string> methodTypeParameters, ImmutableArray<ParameterSignature> methodParameters) { if (!MatchesMethodName(methodDef, typeDef, methodName)) { return false; } if (!MatchesTypeParameterCount(methodTypeParameters, methodDef.GetGenericParameters(), offset: 0)) { return false; } if (methodParameters.IsDefault) { return true; } return MatchesParameters(methodDef, allTypeParameters, containingArity, methodTypeParameters, methodParameters); } private bool MatchesPropertyOrEvent( StringHandle memberName, MethodDefinitionHandle primaryAccessorHandle, string name, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<ParameterSignature> propertyParameters) { if (!MatchesMemberName(memberName, name)) { return false; } if (propertyParameters.IsDefault) { return true; } if (propertyParameters.Length == 0) { // Parameter-less properties/events should be specified // with no parameter list. return false; } // Match parameters against getter/adder. Not supporting // matching against setter for write-only properties. if (primaryAccessorHandle.IsNil) { return false; } var methodDef = _reader.GetMethodDefinition(primaryAccessorHandle); return MatchesParameters(methodDef, allTypeParameters, containingArity, ImmutableArray<string>.Empty, propertyParameters); } private bool MatchesMethodName(in MethodDefinition methodDef, in TypeDefinition declaringTypeDef, string name) { // special names: if ((methodDef.Attributes & MethodAttributes.RTSpecialName) != 0) { // constructor: var ctorName = (methodDef.Attributes & MethodAttributes.Static) == 0 ? WellKnownMemberNames.InstanceConstructorName : WellKnownMemberNames.StaticConstructorName; if (_reader.StringComparer.Equals(methodDef.Name, ctorName, ignoreCase: false) && MatchesTypeName(declaringTypeDef, name)) { return true; } } return MatchesMemberName(methodDef.Name, name); } private bool MatchesMemberName(in StringHandle memberName, string name) { if (_reader.StringComparer.Equals(memberName, name, _ignoreCase)) { return true; } var comparer = _ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; var metadataName = _reader.GetString(memberName); // C# local function if (GeneratedNameParser.TryParseLocalFunctionName(metadataName, out var localFunctionName)) { return comparer.Equals(name, localFunctionName); } // implicitly implemented interface member: var lastDot = metadataName.LastIndexOf('.'); if (lastDot >= 0 && comparer.Equals(metadataName.Substring(lastDot + 1), name)) { return true; } return false; } private ImmutableArray<string> GetAllGenericTypeParameters(Name typeName) { var builder = ImmutableArray.CreateBuilder<string>(); GetAllGenericTypeParameters(typeName, builder); return builder.ToImmutable(); } private void GetAllGenericTypeParameters(Name typeName, ImmutableArray<string>.Builder builder) { if (typeName == null) { return; } QualifiedName qualifiedName; ImmutableArray<string> typeParameters; GetNameAndTypeParameters(typeName, out qualifiedName, out typeParameters); GetAllGenericTypeParameters(qualifiedName.Qualifier, builder); builder.AddRange(typeParameters); } private bool MatchesParameters( MethodDefinition methodDef, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<string> methodTypeParameters, ImmutableArray<ParameterSignature> methodParameters) { ImmutableArray<ParameterSignature> parameters; try { var decoder = new MetadataDecoder(_reader, allTypeParameters, containingArity, methodTypeParameters); parameters = decoder.DecodeParameters(methodDef); } catch (NotSupportedException) { return false; } catch (BadImageFormatException) { return false; } return methodParameters.SequenceEqual(parameters, MatchesParameter); } private void OnFunctionResolved( TRequest request, MethodDefinitionHandle handle) { Debug.Assert(!handle.IsNil); _onFunctionResolved(_module, request, token: MetadataTokens.GetToken(handle), version: 1, ilOffset: 0); } private void OnAccessorResolved( TRequest request, MethodDefinitionHandle handle) { if (handle.IsNil) { return; } var methodDef = _reader.GetMethodDefinition(handle); if (IsResolvableMethod(methodDef)) { OnFunctionResolved(request, handle); } } private static bool MatchesTypeParameterCount(ImmutableArray<string> typeArguments, GenericParameterHandleCollection typeParameters, int offset) { return typeArguments.Length == typeParameters.Count - offset; } // parameterA from string signature, parameterB from metadata. private bool MatchesParameter(ParameterSignature parameterA, ParameterSignature parameterB) { return MatchesType(parameterA.Type, parameterB.Type) && parameterA.IsByRef == parameterB.IsByRef; } // typeA from string signature, typeB from metadata. private bool MatchesType(TypeSignature typeA, TypeSignature typeB) { if (typeA.Kind != typeB.Kind) { return false; } switch (typeA.Kind) { case TypeSignatureKind.GenericType: { var genericA = (GenericTypeSignature)typeA; var genericB = (GenericTypeSignature)typeB; return MatchesType(genericA.QualifiedName, genericB.QualifiedName) && genericA.TypeArguments.SequenceEqual(genericB.TypeArguments, MatchesType); } case TypeSignatureKind.QualifiedType: { var qualifiedA = (QualifiedTypeSignature)typeA; var qualifiedB = (QualifiedTypeSignature)typeB; // Metadata signature may be more qualified than the // string signature but still considered a match // (e.g.: "B<U>.C" should match N.A<T>.B<U>.C). return (qualifiedA.Qualifier == null || (qualifiedB.Qualifier != null && MatchesType(qualifiedA.Qualifier, qualifiedB.Qualifier))) && _stringComparer.Equals(qualifiedA.Name, qualifiedB.Name); } case TypeSignatureKind.ArrayType: { var arrayA = (ArrayTypeSignature)typeA; var arrayB = (ArrayTypeSignature)typeB; return MatchesType(arrayA.ElementType, arrayB.ElementType) && arrayA.Rank == arrayB.Rank; } case TypeSignatureKind.PointerType: { var pointerA = (PointerTypeSignature)typeA; var pointerB = (PointerTypeSignature)typeB; return MatchesType(pointerA.PointedAtType, pointerB.PointedAtType); } default: throw ExceptionUtilities.UnexpectedValue(typeA.Kind); } } private static void GetNameAndTypeParameters( Name name, out QualifiedName qualifiedName, out ImmutableArray<string> typeParameters) { switch (name.Kind) { case NameKind.GenericName: { var genericName = (GenericName)name; qualifiedName = genericName.QualifiedName; typeParameters = genericName.TypeParameters; } break; case NameKind.QualifiedName: { qualifiedName = (QualifiedName)name; typeParameters = ImmutableArray<string>.Empty; } break; default: throw ExceptionUtilities.UnexpectedValue(name.Kind); } } private static bool IsResolvableMethod(MethodDefinition methodDef) { return (methodDef.Attributes & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0; } private static string RemoveAritySeparatorIfAny(string typeName) { int index = typeName.LastIndexOf('`'); return (index < 0) ? typeName : typeName.Substring(0, index); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal delegate void OnFunctionResolvedDelegate<TModule, TRequest>(TModule module, TRequest request, int token, int version, int ilOffset); internal sealed class MetadataResolver<TProcess, TModule, TRequest> where TProcess : class where TModule : class where TRequest : class { private readonly TModule _module; private readonly MetadataReader _reader; private readonly StringComparer _stringComparer; // for comparing strings private readonly bool _ignoreCase; // for comparing strings to strings represented with StringHandles private readonly OnFunctionResolvedDelegate<TModule, TRequest> _onFunctionResolved; internal MetadataResolver( TModule module, MetadataReader reader, bool ignoreCase, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { _module = module; _reader = reader; _stringComparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; _ignoreCase = ignoreCase; _onFunctionResolved = onFunctionResolved; } internal void Resolve(TRequest request, RequestSignature signature) { QualifiedName qualifiedTypeName; ImmutableArray<string> memberTypeParameters; GetNameAndTypeParameters(signature.MemberName, out qualifiedTypeName, out memberTypeParameters); var typeName = qualifiedTypeName.Qualifier; var memberName = qualifiedTypeName.Name; var memberParameters = signature.Parameters; var allTypeParameters = GetAllGenericTypeParameters(typeName); foreach (var typeHandle in _reader.TypeDefinitions) { var typeDef = _reader.GetTypeDefinition(typeHandle); int containingArity = CompareToTypeDefinition(typeDef, typeName); if (containingArity < 0) { continue; } // Visit methods. foreach (var methodHandle in typeDef.GetMethods()) { var methodDef = _reader.GetMethodDefinition(methodHandle); if (!IsResolvableMethod(methodDef)) { continue; } if (MatchesMethod(typeDef, methodDef, memberName, allTypeParameters, containingArity, memberTypeParameters, memberParameters)) { OnFunctionResolved(request, methodHandle); } } if (memberTypeParameters.IsEmpty) { // Visit properties. foreach (var propertyHandle in typeDef.GetProperties()) { var propertyDef = _reader.GetPropertyDefinition(propertyHandle); var accessors = propertyDef.GetAccessors(); if (MatchesPropertyOrEvent(propertyDef.Name, accessors.Getter, memberName, allTypeParameters, containingArity, memberParameters)) { OnAccessorResolved(request, accessors.Getter); OnAccessorResolved(request, accessors.Setter); } } // Visit events. foreach (var eventHandle in typeDef.GetEvents()) { var eventDef = _reader.GetEventDefinition(eventHandle); var accessors = eventDef.GetAccessors(); if (MatchesPropertyOrEvent(eventDef.Name, accessors.Adder, memberName, allTypeParameters, containingArity, memberParameters)) { OnAccessorResolved(request, accessors.Adder); OnAccessorResolved(request, accessors.Remover); } } } } } // If the signature matches the TypeDefinition, including some or all containing // types and namespaces, returns a non-negative value indicating the arity of the // containing types that were not specified in the signature; otherwise returns -1. // For instance, "C<T>.D" will return 1 matching against metadata type N.M.A<T>.B.C<U>.D, // where N.M is a namespace and A<T>, B, C<U>, D are nested types. The value 1 // is the arity of the containing types A<T>.B that were missing from the signature. // "C<T>.D" will not match C<T> or C<T>.D.E since the match must include the entire // signature, from nested TypeDefinition, out. private int CompareToTypeDefinition(TypeDefinition typeDef, Name signature) { if (signature == null) { return typeDef.GetGenericParameters().Count; } QualifiedName qualifiedName; ImmutableArray<string> typeParameters; GetNameAndTypeParameters(signature, out qualifiedName, out typeParameters); if (!MatchesTypeName(typeDef, qualifiedName.Name)) { return -1; } var declaringTypeHandle = typeDef.GetDeclaringType(); var declaringType = declaringTypeHandle.IsNil ? default : _reader.GetTypeDefinition(declaringTypeHandle); int declaringTypeParameterCount = declaringTypeHandle.IsNil ? 0 : declaringType.GetGenericParameters().Count; if (!MatchesTypeParameterCount(typeParameters, typeDef.GetGenericParameters(), declaringTypeParameterCount)) { return -1; } var qualifier = qualifiedName.Qualifier; if (declaringTypeHandle.IsNil) { // Compare namespace. return MatchesNamespace(typeDef, qualifier) ? 0 : -1; } else { // Compare declaring type. return CompareToTypeDefinition(declaringType, qualifier); } } private bool MatchesNamespace(TypeDefinition typeDef, Name signature) { if (signature == null) { return true; } var namespaceName = _reader.GetString(typeDef.Namespace); if (string.IsNullOrEmpty(namespaceName)) { return false; } var parts = namespaceName.Split('.'); for (int index = parts.Length - 1; index >= 0; index--) { if (signature == null) { return true; } var qualifiedName = signature as QualifiedName; if (qualifiedName == null) { return false; } var part = parts[index]; if (!_stringComparer.Equals(qualifiedName.Name, part)) { return false; } signature = qualifiedName.Qualifier; } return signature == null; } private bool MatchesTypeName(TypeDefinition typeDef, string name) { var typeName = RemoveAritySeparatorIfAny(_reader.GetString(typeDef.Name)); return _stringComparer.Equals(typeName, name); } private bool MatchesMethod( TypeDefinition typeDef, MethodDefinition methodDef, string methodName, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<string> methodTypeParameters, ImmutableArray<ParameterSignature> methodParameters) { if (!MatchesMethodName(methodDef, typeDef, methodName)) { return false; } if (!MatchesTypeParameterCount(methodTypeParameters, methodDef.GetGenericParameters(), offset: 0)) { return false; } if (methodParameters.IsDefault) { return true; } return MatchesParameters(methodDef, allTypeParameters, containingArity, methodTypeParameters, methodParameters); } private bool MatchesPropertyOrEvent( StringHandle memberName, MethodDefinitionHandle primaryAccessorHandle, string name, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<ParameterSignature> propertyParameters) { if (!MatchesMemberName(memberName, name)) { return false; } if (propertyParameters.IsDefault) { return true; } if (propertyParameters.Length == 0) { // Parameter-less properties/events should be specified // with no parameter list. return false; } // Match parameters against getter/adder. Not supporting // matching against setter for write-only properties. if (primaryAccessorHandle.IsNil) { return false; } var methodDef = _reader.GetMethodDefinition(primaryAccessorHandle); return MatchesParameters(methodDef, allTypeParameters, containingArity, ImmutableArray<string>.Empty, propertyParameters); } private bool MatchesMethodName(in MethodDefinition methodDef, in TypeDefinition declaringTypeDef, string name) { // special names: if ((methodDef.Attributes & MethodAttributes.RTSpecialName) != 0) { // constructor: var ctorName = (methodDef.Attributes & MethodAttributes.Static) == 0 ? WellKnownMemberNames.InstanceConstructorName : WellKnownMemberNames.StaticConstructorName; if (_reader.StringComparer.Equals(methodDef.Name, ctorName, ignoreCase: false) && MatchesTypeName(declaringTypeDef, name)) { return true; } } return MatchesMemberName(methodDef.Name, name); } private bool MatchesMemberName(in StringHandle memberName, string name) { if (_reader.StringComparer.Equals(memberName, name, _ignoreCase)) { return true; } var comparer = _ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; var metadataName = _reader.GetString(memberName); // C# local function if (GeneratedNameParser.TryParseLocalFunctionName(metadataName, out var localFunctionName)) { return comparer.Equals(name, localFunctionName); } // implicitly implemented interface member: var lastDot = metadataName.LastIndexOf('.'); if (lastDot >= 0 && comparer.Equals(metadataName.Substring(lastDot + 1), name)) { return true; } return false; } private ImmutableArray<string> GetAllGenericTypeParameters(Name typeName) { var builder = ImmutableArray.CreateBuilder<string>(); GetAllGenericTypeParameters(typeName, builder); return builder.ToImmutable(); } private void GetAllGenericTypeParameters(Name typeName, ImmutableArray<string>.Builder builder) { if (typeName == null) { return; } QualifiedName qualifiedName; ImmutableArray<string> typeParameters; GetNameAndTypeParameters(typeName, out qualifiedName, out typeParameters); GetAllGenericTypeParameters(qualifiedName.Qualifier, builder); builder.AddRange(typeParameters); } private bool MatchesParameters( MethodDefinition methodDef, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<string> methodTypeParameters, ImmutableArray<ParameterSignature> methodParameters) { ImmutableArray<ParameterSignature> parameters; try { var decoder = new MetadataDecoder(_reader, allTypeParameters, containingArity, methodTypeParameters); parameters = decoder.DecodeParameters(methodDef); } catch (NotSupportedException) { return false; } catch (BadImageFormatException) { return false; } return methodParameters.SequenceEqual(parameters, MatchesParameter); } private void OnFunctionResolved( TRequest request, MethodDefinitionHandle handle) { Debug.Assert(!handle.IsNil); _onFunctionResolved(_module, request, token: MetadataTokens.GetToken(handle), version: 1, ilOffset: 0); } private void OnAccessorResolved( TRequest request, MethodDefinitionHandle handle) { if (handle.IsNil) { return; } var methodDef = _reader.GetMethodDefinition(handle); if (IsResolvableMethod(methodDef)) { OnFunctionResolved(request, handle); } } private static bool MatchesTypeParameterCount(ImmutableArray<string> typeArguments, GenericParameterHandleCollection typeParameters, int offset) { return typeArguments.Length == typeParameters.Count - offset; } // parameterA from string signature, parameterB from metadata. private bool MatchesParameter(ParameterSignature parameterA, ParameterSignature parameterB) { return MatchesType(parameterA.Type, parameterB.Type) && parameterA.IsByRef == parameterB.IsByRef; } // typeA from string signature, typeB from metadata. private bool MatchesType(TypeSignature typeA, TypeSignature typeB) { if (typeA.Kind != typeB.Kind) { return false; } switch (typeA.Kind) { case TypeSignatureKind.GenericType: { var genericA = (GenericTypeSignature)typeA; var genericB = (GenericTypeSignature)typeB; return MatchesType(genericA.QualifiedName, genericB.QualifiedName) && genericA.TypeArguments.SequenceEqual(genericB.TypeArguments, MatchesType); } case TypeSignatureKind.QualifiedType: { var qualifiedA = (QualifiedTypeSignature)typeA; var qualifiedB = (QualifiedTypeSignature)typeB; // Metadata signature may be more qualified than the // string signature but still considered a match // (e.g.: "B<U>.C" should match N.A<T>.B<U>.C). return (qualifiedA.Qualifier == null || (qualifiedB.Qualifier != null && MatchesType(qualifiedA.Qualifier, qualifiedB.Qualifier))) && _stringComparer.Equals(qualifiedA.Name, qualifiedB.Name); } case TypeSignatureKind.ArrayType: { var arrayA = (ArrayTypeSignature)typeA; var arrayB = (ArrayTypeSignature)typeB; return MatchesType(arrayA.ElementType, arrayB.ElementType) && arrayA.Rank == arrayB.Rank; } case TypeSignatureKind.PointerType: { var pointerA = (PointerTypeSignature)typeA; var pointerB = (PointerTypeSignature)typeB; return MatchesType(pointerA.PointedAtType, pointerB.PointedAtType); } default: throw ExceptionUtilities.UnexpectedValue(typeA.Kind); } } private static void GetNameAndTypeParameters( Name name, out QualifiedName qualifiedName, out ImmutableArray<string> typeParameters) { switch (name.Kind) { case NameKind.GenericName: { var genericName = (GenericName)name; qualifiedName = genericName.QualifiedName; typeParameters = genericName.TypeParameters; } break; case NameKind.QualifiedName: { qualifiedName = (QualifiedName)name; typeParameters = ImmutableArray<string>.Empty; } break; default: throw ExceptionUtilities.UnexpectedValue(name.Kind); } } private static bool IsResolvableMethod(MethodDefinition methodDef) { return (methodDef.Attributes & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0; } private static string RemoveAritySeparatorIfAny(string typeName) { int index = typeName.LastIndexOf('`'); return (index < 0) ? typeName : typeName.Substring(0, index); } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Compilers/Core/Portable/MetadataReference/Metadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { /// <summary> /// An Id that can be used to identify a metadata instance. If two metadata instances /// have the same id then they are guaranteed to have the same content. If two metadata /// instances have different ids, then the contents may or may not be the same. As such, /// the id is useful as a key in a cache when a client wants to share data for a metadata /// reference as long as it has not changed. /// </summary> public sealed class MetadataId { private MetadataId() { } internal static MetadataId CreateNewId() => new MetadataId(); } /// <summary> /// Represents immutable assembly or module CLI metadata. /// </summary> public abstract class Metadata : IDisposable { internal readonly bool IsImageOwner; /// <summary> /// The id for this metadata instance. If two metadata instances have the same id, then /// they have the same content. If they have different ids they may or may not have the /// same content. /// </summary> public MetadataId Id { get; } internal Metadata(bool isImageOwner, MetadataId id) { this.IsImageOwner = isImageOwner; this.Id = id; } /// <summary> /// Retrieves the <see cref="MetadataImageKind"/> for this instance. /// </summary> public abstract MetadataImageKind Kind { get; } /// <summary> /// Releases any resources associated with this instance. /// </summary> public abstract void Dispose(); protected abstract Metadata CommonCopy(); /// <summary> /// Creates a copy of this object. /// </summary> public Metadata Copy() { return CommonCopy(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { /// <summary> /// An Id that can be used to identify a metadata instance. If two metadata instances /// have the same id then they are guaranteed to have the same content. If two metadata /// instances have different ids, then the contents may or may not be the same. As such, /// the id is useful as a key in a cache when a client wants to share data for a metadata /// reference as long as it has not changed. /// </summary> public sealed class MetadataId { private MetadataId() { } internal static MetadataId CreateNewId() => new MetadataId(); } /// <summary> /// Represents immutable assembly or module CLI metadata. /// </summary> public abstract class Metadata : IDisposable { internal readonly bool IsImageOwner; /// <summary> /// The id for this metadata instance. If two metadata instances have the same id, then /// they have the same content. If they have different ids they may or may not have the /// same content. /// </summary> public MetadataId Id { get; } internal Metadata(bool isImageOwner, MetadataId id) { this.IsImageOwner = isImageOwner; this.Id = id; } /// <summary> /// Retrieves the <see cref="MetadataImageKind"/> for this instance. /// </summary> public abstract MetadataImageKind Kind { get; } /// <summary> /// Releases any resources associated with this instance. /// </summary> public abstract void Dispose(); protected abstract Metadata CommonCopy(); /// <summary> /// Creates a copy of this object. /// </summary> public Metadata Copy() { return CommonCopy(); } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/EditorConfig/EditorConfigNamingStyleParser_NamingStyle.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.NamingStyles; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal static partial class EditorConfigNamingStyleParser { private static bool TryGetNamingStyleData( string namingRuleName, IReadOnlyDictionary<string, string> rawOptions, out NamingStyle namingStyle) { namingStyle = default; if (!TryGetNamingStyleTitle(namingRuleName, rawOptions, out var namingStyleTitle)) { return false; } var requiredPrefix = GetNamingRequiredPrefix(namingStyleTitle, rawOptions); var requiredSuffix = GetNamingRequiredSuffix(namingStyleTitle, rawOptions); var wordSeparator = GetNamingWordSeparator(namingStyleTitle, rawOptions); if (!TryGetNamingCapitalization(namingStyleTitle, rawOptions, out var capitalization)) { return false; } namingStyle = new NamingStyle( Guid.NewGuid(), name: namingStyleTitle, prefix: requiredPrefix, suffix: requiredSuffix, wordSeparator: wordSeparator, capitalizationScheme: capitalization); return true; } private static bool TryGetNamingStyleTitle( string namingRuleName, IReadOnlyDictionary<string, string> conventionsDictionary, out string namingStyleName) { if (conventionsDictionary.TryGetValue($"dotnet_naming_rule.{namingRuleName}.style", out namingStyleName)) { return namingStyleName != null; } namingStyleName = null; return false; } private static string GetNamingRequiredPrefix(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary) => GetStringFromConventionsDictionary(namingStyleName, "required_prefix", conventionsDictionary); private static string GetNamingRequiredSuffix(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary) => GetStringFromConventionsDictionary(namingStyleName, "required_suffix", conventionsDictionary); private static string GetNamingWordSeparator(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary) => GetStringFromConventionsDictionary(namingStyleName, "word_separator", conventionsDictionary); private static bool TryGetNamingCapitalization(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary, out Capitalization capitalization) { var result = GetStringFromConventionsDictionary(namingStyleName, "capitalization", conventionsDictionary); return TryParseCapitalizationScheme(result, out capitalization); } private static string GetStringFromConventionsDictionary(string namingStyleName, string optionName, IReadOnlyDictionary<string, string> conventionsDictionary) { conventionsDictionary.TryGetValue($"dotnet_naming_style.{namingStyleName}.{optionName}", out var result); return result ?? string.Empty; } private static bool TryParseCapitalizationScheme(string namingStyleCapitalization, out Capitalization capitalization) { switch (namingStyleCapitalization) { case "pascal_case": capitalization = Capitalization.PascalCase; return true; case "camel_case": capitalization = Capitalization.CamelCase; return true; case "first_word_upper": capitalization = Capitalization.FirstUpper; return true; case "all_upper": capitalization = Capitalization.AllUpper; return true; case "all_lower": capitalization = Capitalization.AllLower; return true; default: capitalization = default; return false; } } public static string ToEditorConfigString(this Capitalization capitalization) { switch (capitalization) { case Capitalization.PascalCase: return "pascal_case"; case Capitalization.CamelCase: return "camel_case"; case Capitalization.FirstUpper: return "first_word_upper"; case Capitalization.AllUpper: return "all_upper"; case Capitalization.AllLower: return "all_lower"; default: throw ExceptionUtilities.UnexpectedValue(capitalization); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.NamingStyles; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal static partial class EditorConfigNamingStyleParser { private static bool TryGetNamingStyleData( string namingRuleName, IReadOnlyDictionary<string, string> rawOptions, out NamingStyle namingStyle) { namingStyle = default; if (!TryGetNamingStyleTitle(namingRuleName, rawOptions, out var namingStyleTitle)) { return false; } var requiredPrefix = GetNamingRequiredPrefix(namingStyleTitle, rawOptions); var requiredSuffix = GetNamingRequiredSuffix(namingStyleTitle, rawOptions); var wordSeparator = GetNamingWordSeparator(namingStyleTitle, rawOptions); if (!TryGetNamingCapitalization(namingStyleTitle, rawOptions, out var capitalization)) { return false; } namingStyle = new NamingStyle( Guid.NewGuid(), name: namingStyleTitle, prefix: requiredPrefix, suffix: requiredSuffix, wordSeparator: wordSeparator, capitalizationScheme: capitalization); return true; } private static bool TryGetNamingStyleTitle( string namingRuleName, IReadOnlyDictionary<string, string> conventionsDictionary, out string namingStyleName) { if (conventionsDictionary.TryGetValue($"dotnet_naming_rule.{namingRuleName}.style", out namingStyleName)) { return namingStyleName != null; } namingStyleName = null; return false; } private static string GetNamingRequiredPrefix(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary) => GetStringFromConventionsDictionary(namingStyleName, "required_prefix", conventionsDictionary); private static string GetNamingRequiredSuffix(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary) => GetStringFromConventionsDictionary(namingStyleName, "required_suffix", conventionsDictionary); private static string GetNamingWordSeparator(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary) => GetStringFromConventionsDictionary(namingStyleName, "word_separator", conventionsDictionary); private static bool TryGetNamingCapitalization(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary, out Capitalization capitalization) { var result = GetStringFromConventionsDictionary(namingStyleName, "capitalization", conventionsDictionary); return TryParseCapitalizationScheme(result, out capitalization); } private static string GetStringFromConventionsDictionary(string namingStyleName, string optionName, IReadOnlyDictionary<string, string> conventionsDictionary) { conventionsDictionary.TryGetValue($"dotnet_naming_style.{namingStyleName}.{optionName}", out var result); return result ?? string.Empty; } private static bool TryParseCapitalizationScheme(string namingStyleCapitalization, out Capitalization capitalization) { switch (namingStyleCapitalization) { case "pascal_case": capitalization = Capitalization.PascalCase; return true; case "camel_case": capitalization = Capitalization.CamelCase; return true; case "first_word_upper": capitalization = Capitalization.FirstUpper; return true; case "all_upper": capitalization = Capitalization.AllUpper; return true; case "all_lower": capitalization = Capitalization.AllLower; return true; default: capitalization = default; return false; } } public static string ToEditorConfigString(this Capitalization capitalization) { switch (capitalization) { case Capitalization.PascalCase: return "pascal_case"; case Capitalization.CamelCase: return "camel_case"; case Capitalization.FirstUpper: return "first_word_upper"; case Capitalization.AllUpper: return "all_upper"; case Capitalization.AllLower: return "all_lower"; default: throw ExceptionUtilities.UnexpectedValue(capitalization); } } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Features/Core/Portable/ImplementInterface/AbstractImplementInterfaceService.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ImplementInterface { internal abstract partial class AbstractImplementInterfaceService { internal class State { public SyntaxNode Location { get; } public SyntaxNode ClassOrStructDecl { get; } public INamedTypeSymbol ClassOrStructType { get; } public IEnumerable<INamedTypeSymbol> InterfaceTypes { get; } public SemanticModel Model { get; } // The members that are not implemented at all. public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitOrImplicitImplementation { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; // The members that have no explicit implementation. public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitImplementation { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; public State(SyntaxNode interfaceNode, SyntaxNode classOrStructDecl, INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaceTypes, SemanticModel model) { Location = interfaceNode; ClassOrStructDecl = classOrStructDecl; ClassOrStructType = classOrStructType; InterfaceTypes = interfaceTypes; Model = model; } public static State Generate( AbstractImplementInterfaceService service, Document document, SemanticModel model, SyntaxNode interfaceNode, CancellationToken cancellationToken) { if (!service.TryInitializeState(document, model, interfaceNode, cancellationToken, out var classOrStructDecl, out var classOrStructType, out var interfaceTypes)) { return null; } if (!CodeGenerator.CanAdd(document.Project.Solution, classOrStructType, cancellationToken)) { return null; } var state = new State(interfaceNode, classOrStructDecl, classOrStructType, interfaceTypes, model); if (service.CanImplementImplicitly) { state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented = state.ClassOrStructType.GetAllUnimplementedMembers( interfaceTypes, includeMembersRequiringExplicitImplementation: false, cancellationToken); state.MembersWithoutExplicitOrImplicitImplementation = state.ClassOrStructType.GetAllUnimplementedMembers( interfaceTypes, includeMembersRequiringExplicitImplementation: true, cancellationToken); state.MembersWithoutExplicitImplementation = state.ClassOrStructType.GetAllUnimplementedExplicitMembers( interfaceTypes, cancellationToken); var allMembersImplemented = state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length == 0; var allMembersImplementedExplicitly = state.MembersWithoutExplicitImplementation.Length == 0; return !allMembersImplementedExplicitly || !allMembersImplemented ? state : null; } else { // We put the members in this bucket so that the code fix title is "Implement Interface" state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented = state.ClassOrStructType.GetAllUnimplementedExplicitMembers( interfaceTypes, cancellationToken); var allMembersImplemented = state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length == 0; return !allMembersImplemented ? state : null; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ImplementInterface { internal abstract partial class AbstractImplementInterfaceService { internal class State { public SyntaxNode Location { get; } public SyntaxNode ClassOrStructDecl { get; } public INamedTypeSymbol ClassOrStructType { get; } public IEnumerable<INamedTypeSymbol> InterfaceTypes { get; } public SemanticModel Model { get; } // The members that are not implemented at all. public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitOrImplicitImplementation { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; // The members that have no explicit implementation. public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitImplementation { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; public State(SyntaxNode interfaceNode, SyntaxNode classOrStructDecl, INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaceTypes, SemanticModel model) { Location = interfaceNode; ClassOrStructDecl = classOrStructDecl; ClassOrStructType = classOrStructType; InterfaceTypes = interfaceTypes; Model = model; } public static State Generate( AbstractImplementInterfaceService service, Document document, SemanticModel model, SyntaxNode interfaceNode, CancellationToken cancellationToken) { if (!service.TryInitializeState(document, model, interfaceNode, cancellationToken, out var classOrStructDecl, out var classOrStructType, out var interfaceTypes)) { return null; } if (!CodeGenerator.CanAdd(document.Project.Solution, classOrStructType, cancellationToken)) { return null; } var state = new State(interfaceNode, classOrStructDecl, classOrStructType, interfaceTypes, model); if (service.CanImplementImplicitly) { state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented = state.ClassOrStructType.GetAllUnimplementedMembers( interfaceTypes, includeMembersRequiringExplicitImplementation: false, cancellationToken); state.MembersWithoutExplicitOrImplicitImplementation = state.ClassOrStructType.GetAllUnimplementedMembers( interfaceTypes, includeMembersRequiringExplicitImplementation: true, cancellationToken); state.MembersWithoutExplicitImplementation = state.ClassOrStructType.GetAllUnimplementedExplicitMembers( interfaceTypes, cancellationToken); var allMembersImplemented = state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length == 0; var allMembersImplementedExplicitly = state.MembersWithoutExplicitImplementation.Length == 0; return !allMembersImplementedExplicitly || !allMembersImplemented ? state : null; } else { // We put the members in this bucket so that the code fix title is "Implement Interface" state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented = state.ClassOrStructType.GetAllUnimplementedExplicitMembers( interfaceTypes, cancellationToken); var allMembersImplemented = state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length == 0; return !allMembersImplemented ? state : null; } } } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Workspaces/Core/Portable/Options/IDocumentOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Returned from a <see cref="IDocumentOptionsProvider"/> /// </summary> internal interface IDocumentOptions { /// <summary> /// Attempts to fetch the value for the given option. /// </summary> /// <param name="option"></param> /// <param name="value">The value returned. May be null even if the function returns true as "null" may be valid value for some options.</param> /// <returns>True if this provider had a specific value for this option. False to indicate other providers should be queried.</returns> bool TryGetDocumentOption(OptionKey option, out object? value); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Returned from a <see cref="IDocumentOptionsProvider"/> /// </summary> internal interface IDocumentOptions { /// <summary> /// Attempts to fetch the value for the given option. /// </summary> /// <param name="option"></param> /// <param name="value">The value returned. May be null even if the function returns true as "null" may be valid value for some options.</param> /// <returns>True if this provider had a specific value for this option. False to indicate other providers should be queried.</returns> bool TryGetDocumentOption(OptionKey option, out object? value); } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/VisualStudio/CSharp/Impl/Options/Formatting/FormattingNewLinesPage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { [Guid(Guids.CSharpOptionPageFormattingNewLinesIdString)] internal class FormattingNewLinesPage : AbstractOptionPage { public FormattingNewLinesPage() { } protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore) => new OptionPreviewControl(serviceProvider, optionStore, (o, s) => new NewLinesViewModel(o, s)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { [Guid(Guids.CSharpOptionPageFormattingNewLinesIdString)] internal class FormattingNewLinesPage : AbstractOptionPage { public FormattingNewLinesPage() { } protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore) => new OptionPreviewControl(serviceProvider, optionStore, (o, s) => new NewLinesViewModel(o, s)); } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { using MetadataOrDiagnostic = System.Object; /// <summary> /// The base class for language specific assembly managers. /// </summary> /// <typeparam name="TCompilation">Language specific representation for a compilation</typeparam> /// <typeparam name="TAssemblySymbol">Language specific representation for an assembly symbol.</typeparam> internal abstract partial class CommonReferenceManager<TCompilation, TAssemblySymbol> where TCompilation : Compilation where TAssemblySymbol : class, IAssemblySymbolInternal { protected abstract CommonMessageProvider MessageProvider { get; } protected abstract AssemblyData CreateAssemblyDataForFile( PEAssembly assembly, WeakList<IAssemblySymbolInternal> cachedSymbols, DocumentationProvider documentationProvider, string sourceAssemblySimpleName, MetadataImportOptions importOptions, bool embedInteropTypes); protected abstract AssemblyData CreateAssemblyDataForCompilation( CompilationReference compilationReference); /// <summary> /// Checks if the properties of <paramref name="duplicateReference"/> are compatible with properties of <paramref name="primaryReference"/>. /// Reports inconsistencies to the given diagnostic bag. /// </summary> /// <returns>True if the properties are compatible and hence merged, false if the duplicate reference should not merge it's properties with primary reference.</returns> protected abstract bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics); /// <summary> /// Called to compare two weakly named identities with the same name. /// </summary> protected abstract bool WeakIdentityPropertiesEquivalent(AssemblyIdentity identity1, AssemblyIdentity identity2); [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] protected struct ResolvedReference { private readonly MetadataImageKind _kind; private readonly int _index; private readonly ImmutableArray<string> _aliasesOpt; private readonly ImmutableArray<string> _recursiveAliasesOpt; private readonly ImmutableArray<MetadataReference> _mergedReferencesOpt; // uninitialized aliases public ResolvedReference(int index, MetadataImageKind kind) { Debug.Assert(index >= 0); _index = index + 1; _kind = kind; _aliasesOpt = default(ImmutableArray<string>); _recursiveAliasesOpt = default(ImmutableArray<string>); _mergedReferencesOpt = default(ImmutableArray<MetadataReference>); } // initialized aliases public ResolvedReference(int index, MetadataImageKind kind, ImmutableArray<string> aliasesOpt, ImmutableArray<string> recursiveAliasesOpt, ImmutableArray<MetadataReference> mergedReferences) : this(index, kind) { // We have to have non-default aliases (empty are ok). We can have both recursive and non-recursive aliases if two references were merged. Debug.Assert(!aliasesOpt.IsDefault || !recursiveAliasesOpt.IsDefault); Debug.Assert(!mergedReferences.IsDefault); _aliasesOpt = aliasesOpt; _recursiveAliasesOpt = recursiveAliasesOpt; _mergedReferencesOpt = mergedReferences; } private bool IsUninitialized => (_aliasesOpt.IsDefault && _recursiveAliasesOpt.IsDefault) || _mergedReferencesOpt.IsDefault; /// <summary> /// Aliases that should be applied to the referenced assembly. /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification). /// Null if not applicable (the reference only has recursive aliases). /// </summary> public ImmutableArray<string> AliasesOpt { get { Debug.Assert(!IsUninitialized); return _aliasesOpt; } } /// <summary> /// Aliases that should be applied recursively to all dependent assemblies. /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification). /// Null if not applicable (the reference only has simple aliases). /// </summary> public ImmutableArray<string> RecursiveAliasesOpt { get { Debug.Assert(!IsUninitialized); return _recursiveAliasesOpt; } } public ImmutableArray<MetadataReference> MergedReferences { get { Debug.Assert(!IsUninitialized); return _mergedReferencesOpt; } } /// <summary> /// default(<see cref="ResolvedReference"/>) is considered skipped. /// </summary> public bool IsSkipped { get { return _index == 0; } } public MetadataImageKind Kind { get { Debug.Assert(!IsSkipped); return _kind; } } /// <summary> /// Index into an array of assemblies (not including the assembly being built) or an array of modules, depending on <see cref="Kind"/>. /// </summary> public int Index { get { Debug.Assert(!IsSkipped); return _index - 1; } } private string GetDebuggerDisplay() { return IsSkipped ? "<skipped>" : $"{(_kind == MetadataImageKind.Assembly ? "A" : "M")}[{Index}]:{DisplayAliases(_aliasesOpt, "aliases")}{DisplayAliases(_recursiveAliasesOpt, "recursive-aliases")}"; } private static string DisplayAliases(ImmutableArray<string> aliasesOpt, string name) { return aliasesOpt.IsDefault ? "" : $" {name} = '{string.Join("','", aliasesOpt)}'"; } } protected readonly struct ReferencedAssemblyIdentity { public readonly AssemblyIdentity? Identity; public readonly MetadataReference? Reference; /// <summary> /// non-negative: Index into the array of all (explicitly and implicitly) referenced assemblies. /// negative: ExplicitlyReferencedAssemblies.Count + RelativeAssemblyIndex is an index into the array of assemblies. /// </summary> public readonly int RelativeAssemblyIndex; public int GetAssemblyIndex(int explicitlyReferencedAssemblyCount) => RelativeAssemblyIndex >= 0 ? RelativeAssemblyIndex : explicitlyReferencedAssemblyCount + RelativeAssemblyIndex; public ReferencedAssemblyIdentity(AssemblyIdentity identity, MetadataReference reference, int relativeAssemblyIndex) { Identity = identity; Reference = reference; RelativeAssemblyIndex = relativeAssemblyIndex; } } /// <summary> /// Resolves given metadata references to assemblies and modules. /// </summary> /// <param name="compilation">The compilation whose references are being resolved.</param> /// <param name="assemblyReferencesBySimpleName"> /// Used to filter out assemblies that have the same strong or weak identity. /// Maps simple name to a list of identities. The highest version of each name is the first. /// </param> /// <param name="references">List where to store resolved references. References from #r directives will follow references passed to the compilation constructor.</param> /// <param name="boundReferenceDirectiveMap">Maps #r values to successfully resolved metadata references. Does not contain values that failed to resolve.</param> /// <param name="boundReferenceDirectives">Unique metadata references resolved from #r directives.</param> /// <param name="assemblies">List where to store information about resolved assemblies to.</param> /// <param name="modules">List where to store information about resolved modules to.</param> /// <param name="diagnostics">Diagnostic bag where to report resolution errors.</param> /// <returns> /// Maps index to <paramref name="references"/> to an index of a resolved assembly or module in <paramref name="assemblies"/> or <paramref name="modules"/>, respectively. ///</returns> protected ImmutableArray<ResolvedReference> ResolveMetadataReferences( TCompilation compilation, [Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName, out ImmutableArray<MetadataReference> references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectiveMap, out ImmutableArray<MetadataReference> boundReferenceDirectives, out ImmutableArray<AssemblyData> assemblies, out ImmutableArray<PEModule> modules, DiagnosticBag diagnostics) { // Locations of all #r directives in the order they are listed in the references list. ImmutableArray<Location> referenceDirectiveLocations; GetCompilationReferences(compilation, diagnostics, out references, out boundReferenceDirectiveMap, out referenceDirectiveLocations); // References originating from #r directives precede references supplied as arguments of the compilation. int referenceCount = references.Length; int referenceDirectiveCount = (referenceDirectiveLocations != null ? referenceDirectiveLocations.Length : 0); var referenceMap = new ResolvedReference[referenceCount]; // Maps references that were added to the reference set (i.e. not filtered out as duplicates) to a set of names that // can be used to alias these references. Duplicate assemblies contribute their aliases into this set. Dictionary<MetadataReference, MergedAliases>? lazyAliasMap = null; // Used to filter out duplicate references that reference the same file (resolve to the same full normalized path). var boundReferences = new Dictionary<MetadataReference, MetadataReference>(MetadataReferenceEqualityComparer.Instance); ArrayBuilder<MetadataReference>? uniqueDirectiveReferences = (referenceDirectiveLocations != null) ? ArrayBuilder<MetadataReference>.GetInstance() : null; var assembliesBuilder = ArrayBuilder<AssemblyData>.GetInstance(); ArrayBuilder<PEModule>? lazyModulesBuilder = null; bool supersedeLowerVersions = compilation.Options.ReferencesSupersedeLowerVersions; // When duplicate references with conflicting EmbedInteropTypes flag are encountered, // VB uses the flag from the last one, C# reports an error. We need to enumerate in reverse order // so that we find the one that matters first. for (int referenceIndex = referenceCount - 1; referenceIndex >= 0; referenceIndex--) { var boundReference = references[referenceIndex]; if (boundReference == null) { continue; } // add bound reference if it doesn't exist yet, merging aliases: MetadataReference? existingReference; if (boundReferences.TryGetValue(boundReference, out existingReference)) { // merge properties of compilation-based references if the underlying compilations are the same if ((object)boundReference != existingReference) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); } continue; } boundReferences.Add(boundReference, boundReference); Location location; if (referenceIndex < referenceDirectiveCount) { location = referenceDirectiveLocations[referenceIndex]; uniqueDirectiveReferences!.Add(boundReference); } else { location = Location.None; } // compilation reference var compilationReference = boundReference as CompilationReference; if (compilationReference != null) { switch (compilationReference.Properties.Kind) { case MetadataImageKind.Assembly: existingReference = TryAddAssembly( compilationReference.Compilation.Assembly.Identity, boundReference, -assembliesBuilder.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, supersedeLowerVersions); if (existingReference != null) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); continue; } // Note, if SourceAssemblySymbol hasn't been created for // compilationAssembly.Compilation yet, we want this to happen // right now. Conveniently, this constructor will trigger creation of the // SourceAssemblySymbol. var asmData = CreateAssemblyDataForCompilation(compilationReference); AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder); break; default: throw ExceptionUtilities.UnexpectedValue(compilationReference.Properties.Kind); } continue; } // PE reference var peReference = (PortableExecutableReference)boundReference; Metadata? metadata = GetMetadata(peReference, MessageProvider, location, diagnostics); Debug.Assert(metadata != null || diagnostics.HasAnyErrors()); if (metadata != null) { switch (peReference.Properties.Kind) { case MetadataImageKind.Assembly: var assemblyMetadata = (AssemblyMetadata)metadata; WeakList<IAssemblySymbolInternal> cachedSymbols = assemblyMetadata.CachedSymbols; if (assemblyMetadata.IsValidAssembly()) { PEAssembly? assembly = assemblyMetadata.GetAssembly(); Debug.Assert(assembly is object); existingReference = TryAddAssembly( assembly.Identity, peReference, -assembliesBuilder.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, supersedeLowerVersions); if (existingReference != null) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); continue; } var asmData = CreateAssemblyDataForFile( assembly, cachedSymbols, peReference.DocumentationProvider, SimpleAssemblyName, compilation.Options.MetadataImportOptions, peReference.Properties.EmbedInteropTypes); AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder); } else { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, location, peReference.Display ?? "")); } // asmData keeps strong ref after this point GC.KeepAlive(assemblyMetadata); break; case MetadataImageKind.Module: var moduleMetadata = (ModuleMetadata)metadata; if (moduleMetadata.Module.IsLinkedModule) { // We don't support netmodules since some checks in the compiler need information from the full PE image // (Machine, Bit32Required, PE image hash). if (!moduleMetadata.Module.IsEntireImageAvailable) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage, location, peReference.Display ?? "")); } AddModule(moduleMetadata.Module, referenceIndex, referenceMap, ref lazyModulesBuilder); } else { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotModule, location, peReference.Display ?? "")); } break; default: throw ExceptionUtilities.UnexpectedValue(peReference.Properties.Kind); } } } if (uniqueDirectiveReferences != null) { uniqueDirectiveReferences.ReverseContents(); boundReferenceDirectives = uniqueDirectiveReferences.ToImmutableAndFree(); } else { boundReferenceDirectives = ImmutableArray<MetadataReference>.Empty; } // We enumerated references in reverse order in the above code // and thus assemblies and modules in the builders are reversed. // Fix up all the indices and reverse the builder content now to get // the ordering matching the references. // // Also fills in aliases. for (int i = 0; i < referenceMap.Length; i++) { if (!referenceMap[i].IsSkipped) { int count = (referenceMap[i].Kind == MetadataImageKind.Assembly) ? assembliesBuilder.Count : lazyModulesBuilder?.Count ?? 0; int reversedIndex = count - 1 - referenceMap[i].Index; referenceMap[i] = GetResolvedReferenceAndFreePropertyMapEntry(references[i], reversedIndex, referenceMap[i].Kind, lazyAliasMap); } } assembliesBuilder.ReverseContents(); assemblies = assembliesBuilder.ToImmutableAndFree(); if (lazyModulesBuilder == null) { modules = ImmutableArray<PEModule>.Empty; } else { lazyModulesBuilder.ReverseContents(); modules = lazyModulesBuilder.ToImmutableAndFree(); } return ImmutableArray.CreateRange(referenceMap); } private static ResolvedReference GetResolvedReferenceAndFreePropertyMapEntry(MetadataReference reference, int index, MetadataImageKind kind, Dictionary<MetadataReference, MergedAliases>? propertyMapOpt) { ImmutableArray<string> aliasesOpt, recursiveAliasesOpt; var mergedReferences = ImmutableArray<MetadataReference>.Empty; if (propertyMapOpt != null && propertyMapOpt.TryGetValue(reference, out MergedAliases? mergedProperties)) { aliasesOpt = mergedProperties.AliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>); recursiveAliasesOpt = mergedProperties.RecursiveAliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>); if (mergedProperties.MergedReferencesOpt is object) { mergedReferences = mergedProperties.MergedReferencesOpt.ToImmutableAndFree(); } } else if (reference.Properties.HasRecursiveAliases) { aliasesOpt = default(ImmutableArray<string>); recursiveAliasesOpt = reference.Properties.Aliases; } else { aliasesOpt = reference.Properties.Aliases; recursiveAliasesOpt = default(ImmutableArray<string>); } return new ResolvedReference(index, kind, aliasesOpt, recursiveAliasesOpt, mergedReferences); } /// <summary> /// Creates or gets metadata for PE reference. /// </summary> /// <remarks> /// If any of the following exceptions: <see cref="BadImageFormatException"/>, <see cref="FileNotFoundException"/>, <see cref="IOException"/>, /// are thrown while reading the metadata file, the exception is caught and an appropriate diagnostic stored in <paramref name="diagnostics"/>. /// </remarks> private Metadata? GetMetadata(PortableExecutableReference peReference, CommonMessageProvider messageProvider, Location location, DiagnosticBag diagnostics) { Metadata? existingMetadata; lock (ObservedMetadata) { if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata)) { return existingMetadata; } } Metadata? newMetadata; Diagnostic? newDiagnostic = null; try { newMetadata = peReference.GetMetadataNoCopy(); // make sure basic structure of the PE image is valid: if (newMetadata is AssemblyMetadata assemblyMetadata) { _ = assemblyMetadata.IsValidAssembly(); } else { _ = ((ModuleMetadata)newMetadata).Module.IsLinkedModule; } } catch (Exception e) when (e is BadImageFormatException || e is IOException) { newDiagnostic = PortableExecutableReference.ExceptionToDiagnostic(e, messageProvider, location, peReference.Display ?? "", peReference.Properties.Kind); newMetadata = null; } lock (ObservedMetadata) { if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata)) { return existingMetadata; } if (newDiagnostic != null) { diagnostics.Add(newDiagnostic); } ObservedMetadata.Add(peReference, (MetadataOrDiagnostic?)newMetadata ?? newDiagnostic!); return newMetadata; } } private bool TryGetObservedMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics, out Metadata? metadata) { if (ObservedMetadata.TryGetValue(peReference, out MetadataOrDiagnostic? existing)) { Debug.Assert(existing is Metadata || existing is Diagnostic); metadata = existing as Metadata; if (metadata == null) { diagnostics.Add((Diagnostic)existing); } return true; } metadata = null; return false; } internal AssemblyMetadata? GetAssemblyMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics) { var metadata = GetMetadata(peReference, MessageProvider, Location.None, diagnostics); Debug.Assert(metadata != null || diagnostics.HasAnyErrors()); if (metadata == null) { return null; } // require the metadata to be a valid assembly metadata: var assemblyMetadata = metadata as AssemblyMetadata; if (assemblyMetadata?.IsValidAssembly() != true) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, Location.None, peReference.Display ?? "")); return null; } return assemblyMetadata; } /// <summary> /// Determines whether references are the same. Compilation references are the same if they refer to the same compilation. /// Otherwise, references are represented by their object identities. /// </summary> internal sealed class MetadataReferenceEqualityComparer : IEqualityComparer<MetadataReference> { internal static readonly MetadataReferenceEqualityComparer Instance = new MetadataReferenceEqualityComparer(); public bool Equals(MetadataReference? x, MetadataReference? y) { if (ReferenceEquals(x, y)) { return true; } var cx = x as CompilationReference; if (cx != null) { var cy = y as CompilationReference; if (cy != null) { return (object)cx.Compilation == cy.Compilation; } } return false; } public int GetHashCode(MetadataReference reference) { var compilationReference = reference as CompilationReference; if (compilationReference != null) { return RuntimeHelpers.GetHashCode(compilationReference.Compilation); } return RuntimeHelpers.GetHashCode(reference); } } /// <summary> /// Merges aliases of the first observed reference (<paramref name="primaryReference"/>) with aliases specified for an equivalent reference (<paramref name="newReference"/>). /// Empty alias list is considered to be the same as a list containing "global", since in both cases C# allows unqualified access to the symbols. /// </summary> private void MergeReferenceProperties(MetadataReference primaryReference, MetadataReference newReference, DiagnosticBag diagnostics, ref Dictionary<MetadataReference, MergedAliases>? lazyAliasMap) { if (!CheckPropertiesConsistency(newReference, primaryReference, diagnostics)) { return; } if (lazyAliasMap == null) { lazyAliasMap = new Dictionary<MetadataReference, MergedAliases>(); } MergedAliases? mergedAliases; if (!lazyAliasMap.TryGetValue(primaryReference, out mergedAliases)) { mergedAliases = new MergedAliases(); lazyAliasMap.Add(primaryReference, mergedAliases); mergedAliases.Merge(primaryReference); } mergedAliases.Merge(newReference); } /// <remarks> /// Caller is responsible for freeing any allocated ArrayBuilders. /// </remarks> private static void AddAssembly(AssemblyData data, int referenceIndex, ResolvedReference[] referenceMap, ArrayBuilder<AssemblyData> assemblies) { // aliases will be filled in later: referenceMap[referenceIndex] = new ResolvedReference(assemblies.Count, MetadataImageKind.Assembly); assemblies.Add(data); } /// <remarks> /// Caller is responsible for freeing any allocated ArrayBuilders. /// </remarks> private static void AddModule(PEModule module, int referenceIndex, ResolvedReference[] referenceMap, [NotNull] ref ArrayBuilder<PEModule>? modules) { if (modules == null) { modules = ArrayBuilder<PEModule>.GetInstance(); } referenceMap[referenceIndex] = new ResolvedReference(modules.Count, MetadataImageKind.Module); modules.Add(module); } /// <summary> /// Returns null if an assembly of an equivalent identity has not been added previously, otherwise returns the reference that added it. /// Two identities are considered equivalent if /// - both assembly names are strong (have keys) and are either equal or FX unified /// - both assembly names are weak (no keys) and have the same simple name. /// </summary> private MetadataReference? TryAddAssembly( AssemblyIdentity identity, MetadataReference reference, int assemblyIndex, DiagnosticBag diagnostics, Location location, Dictionary<string, List<ReferencedAssemblyIdentity>> referencesBySimpleName, bool supersedeLowerVersions) { var referencedAssembly = new ReferencedAssemblyIdentity(identity, reference, assemblyIndex); List<ReferencedAssemblyIdentity>? sameSimpleNameIdentities; if (!referencesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities)) { referencesBySimpleName.Add(identity.Name, new List<ReferencedAssemblyIdentity> { referencedAssembly }); return null; } if (supersedeLowerVersions) { foreach (var other in sameSimpleNameIdentities) { Debug.Assert(other.Identity is object); if (identity.Version == other.Identity.Version) { return other.Reference; } } // Keep all versions of the assembly and the first identity in the list the one with the highest version: if (sameSimpleNameIdentities[0].Identity!.Version > identity.Version) { sameSimpleNameIdentities.Add(referencedAssembly); } else { sameSimpleNameIdentities.Add(sameSimpleNameIdentities[0]); sameSimpleNameIdentities[0] = referencedAssembly; } return null; } ReferencedAssemblyIdentity equivalent = default(ReferencedAssemblyIdentity); if (identity.IsStrongName) { foreach (var other in sameSimpleNameIdentities) { // Only compare strong with strong (weak is never equivalent to strong and vice versa). // In order to eliminate duplicate references we need to try to match their identities in both directions since // ReferenceMatchesDefinition is not necessarily symmetric. // (e.g. System.Numerics.Vectors, Version=4.1+ matches System.Numerics.Vectors, Version=4.0, but not the other way around.) Debug.Assert(other.Identity is object); if (other.Identity.IsStrongName && IdentityComparer.ReferenceMatchesDefinition(identity, other.Identity) && IdentityComparer.ReferenceMatchesDefinition(other.Identity, identity)) { equivalent = other; break; } } } else { foreach (var other in sameSimpleNameIdentities) { // only compare weak with weak Debug.Assert(other.Identity is object); if (!other.Identity.IsStrongName && WeakIdentityPropertiesEquivalent(identity, other.Identity)) { equivalent = other; break; } } } if (equivalent.Identity == null) { sameSimpleNameIdentities.Add(referencedAssembly); return null; } // equivalent found - ignore and/or report an error: if (identity.IsStrongName) { Debug.Assert(equivalent.Identity.IsStrongName); // versions might have been unified for a Framework assembly: if (identity != equivalent.Identity) { // Dev12 C# reports an error // Dev12 VB keeps both references in the compilation and reports an ambiguity error when a symbol is used. // BREAKING CHANGE in VB: we report an error for both languages // Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references. MessageProvider.ReportDuplicateMetadataReferenceStrong(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity); } // If the versions match exactly we ignore duplicates w/o reporting errors while // Dev12 C# reports: // error CS1703: An assembly with the same identity '{0}' has already been imported. Try removing one of the duplicate references. // Dev12 VB reports: // Fatal error BC2000 : compiler initialization failed unexpectedly: Project already has a reference to assembly System. // A second reference to 'D:\Temp\System.dll' cannot be added. } else { Debug.Assert(!equivalent.Identity.IsStrongName); // Dev12 reports an error for all weak-named assemblies, even if the versions are the same. // We treat assemblies with the same name and version equal even if they don't have a strong name. // This change allows us to de-duplicate #r references based on identities rather than full paths, // and is closer to platforms that don't support strong names and consider name and version enough // to identify an assembly. An identity without version is considered to have version 0.0.0.0. if (identity != equivalent.Identity) { MessageProvider.ReportDuplicateMetadataReferenceWeak(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity); } } Debug.Assert(equivalent.Reference != null); return equivalent.Reference; } protected void GetCompilationReferences( TCompilation compilation, DiagnosticBag diagnostics, out ImmutableArray<MetadataReference> references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectives, out ImmutableArray<Location> referenceDirectiveLocations) { ArrayBuilder<MetadataReference> referencesBuilder = ArrayBuilder<MetadataReference>.GetInstance(); ArrayBuilder<Location>? referenceDirectiveLocationsBuilder = null; IDictionary<(string, string), MetadataReference>? localBoundReferenceDirectives = null; try { foreach (var referenceDirective in compilation.ReferenceDirectives) { Debug.Assert(referenceDirective.Location is object); if (compilation.Options.MetadataReferenceResolver == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataReferencesNotSupported, referenceDirective.Location)); break; } // we already successfully bound #r with the same value: Debug.Assert(referenceDirective.File is object); Debug.Assert(referenceDirective.Location.SourceTree is object); if (localBoundReferenceDirectives != null && localBoundReferenceDirectives.ContainsKey((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 (localBoundReferenceDirectives == null) { localBoundReferenceDirectives = new Dictionary<(string, string), MetadataReference>(); referenceDirectiveLocationsBuilder = ArrayBuilder<Location>.GetInstance(); } referencesBuilder.Add(boundReference); referenceDirectiveLocationsBuilder!.Add(referenceDirective.Location); localBoundReferenceDirectives.Add((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 (localBoundReferenceDirectives == null) { // no directive references resolved successfully: localBoundReferenceDirectives = SpecializedCollections.EmptyDictionary<(string, string), MetadataReference>(); } boundReferenceDirectives = localBoundReferenceDirectives; 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(); } } /// <summary> /// For each given directive return a bound PE reference, or null if the binding fails. /// </summary> private static PortableExecutableReference? ResolveReferenceDirective(string reference, Location location, TCompilation compilation) { var tree = location.SourceTree; string? basePath = (tree != null && tree.FilePath.Length > 0) ? tree.FilePath : null; // checked earlier: Debug.Assert(compilation.Options.MetadataReferenceResolver != null); var references = compilation.Options.MetadataReferenceResolver.ResolveReference(reference, basePath, MetadataReferenceProperties.Assembly.WithRecursiveAliases(true)); if (references.IsDefaultOrEmpty) { return null; } if (references.Length > 1) { // TODO: implement throw new NotSupportedException(); } return references[0]; } internal static AssemblyReferenceBinding[] ResolveReferencedAssemblies( ImmutableArray<AssemblyIdentity> references, ImmutableArray<AssemblyData> definitions, int definitionStartIndex, AssemblyIdentityComparer assemblyIdentityComparer) { var boundReferences = new AssemblyReferenceBinding[references.Length]; for (int j = 0; j < references.Length; j++) { boundReferences[j] = ResolveReferencedAssembly(references[j], definitions, definitionStartIndex, assemblyIdentityComparer); } return boundReferences; } /// <summary> /// Used to match AssemblyRef with AssemblyDef. /// </summary> /// <param name="definitions">Array of definition identities to match against.</param> /// <param name="definitionStartIndex">An index of the first definition to consider, <paramref name="definitions"/> preceding this index are ignored.</param> /// <param name="reference">Reference identity to resolve.</param> /// <param name="assemblyIdentityComparer">Assembly identity comparer.</param> /// <returns> /// Returns an index the reference is bound. /// </returns> internal static AssemblyReferenceBinding ResolveReferencedAssembly( AssemblyIdentity reference, ImmutableArray<AssemblyData> definitions, int definitionStartIndex, AssemblyIdentityComparer assemblyIdentityComparer) { // Dev11 C# compiler allows the versions to not match exactly, assuming that a newer library may be used instead of an older version. // For a given reference it finds a definition with the lowest version that is higher then or equal to the reference version. // If match.Version != reference.Version a warning is reported. // definition with the lowest version higher than reference version, unless exact version found int minHigherVersionDefinition = -1; int maxLowerVersionDefinition = -1; // Skip assembly being built for now; it will be considered at the very end: bool resolveAgainstAssemblyBeingBuilt = definitionStartIndex == 0; definitionStartIndex = Math.Max(definitionStartIndex, 1); for (int i = definitionStartIndex; i < definitions.Length; i++) { AssemblyIdentity definition = definitions[i].Identity; switch (assemblyIdentityComparer.Compare(reference, definition)) { case AssemblyIdentityComparer.ComparisonResult.NotEquivalent: continue; case AssemblyIdentityComparer.ComparisonResult.Equivalent: return new AssemblyReferenceBinding(reference, i); case AssemblyIdentityComparer.ComparisonResult.EquivalentIgnoringVersion: if (reference.Version < definition.Version) { // Refers to an older assembly than we have if (minHigherVersionDefinition == -1 || definition.Version < definitions[minHigherVersionDefinition].Identity.Version) { minHigherVersionDefinition = i; } } else { Debug.Assert(reference.Version > definition.Version); // Refers to a newer assembly than we have if (maxLowerVersionDefinition == -1 || definition.Version > definitions[maxLowerVersionDefinition].Identity.Version) { maxLowerVersionDefinition = i; } } continue; default: throw ExceptionUtilities.Unreachable; } } // we haven't found definition that matches the reference if (minHigherVersionDefinition != -1) { return new AssemblyReferenceBinding(reference, minHigherVersionDefinition, versionDifference: +1); } if (maxLowerVersionDefinition != -1) { return new AssemblyReferenceBinding(reference, maxLowerVersionDefinition, versionDifference: -1); } // Handle cases where Windows.winmd is a runtime substitute for a // reference to a compile-time winmd. This is for scenarios such as a // debugger EE which constructs a compilation from the modules of // the running process where Windows.winmd loaded at runtime is a // substitute for a collection of Windows.*.winmd compile-time references. if (reference.IsWindowsComponent()) { for (int i = definitionStartIndex; i < definitions.Length; i++) { if (definitions[i].Identity.IsWindowsRuntime()) { return new AssemblyReferenceBinding(reference, i); } } } // In the IDE it is possible the reference we're looking for is a // compilation reference to a source assembly. However, if the reference // is of ContentType WindowsRuntime then the compilation will never // match since all C#/VB WindowsRuntime compilations output .winmdobjs, // not .winmds, and the ContentType of a .winmdobj is Default. // If this is the case, we want to ignore the ContentType mismatch and // allow the compilation to match the reference. if (reference.ContentType == AssemblyContentType.WindowsRuntime) { for (int i = definitionStartIndex; i < definitions.Length; i++) { var definition = definitions[i].Identity; var sourceCompilation = definitions[i].SourceCompilation; if (definition.ContentType == AssemblyContentType.Default && sourceCompilation?.Options.OutputKind == OutputKind.WindowsRuntimeMetadata && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definition.Name) && reference.Version.Equals(definition.Version) && reference.IsRetargetable == definition.IsRetargetable && AssemblyIdentityComparer.CultureComparer.Equals(reference.CultureName, definition.CultureName) && AssemblyIdentity.KeysEqual(reference, definition)) { return new AssemblyReferenceBinding(reference, i); } } } // As in the native compiler (see IMPORTER::MapAssemblyRefToAid), we compare against the // compilation (i.e. source) assembly as a last resort. We follow the native approach of // skipping the public key comparison since we have yet to compute it. if (resolveAgainstAssemblyBeingBuilt && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definitions[0].Identity.Name)) { Debug.Assert(definitions[0].Identity.PublicKeyToken.IsEmpty); return new AssemblyReferenceBinding(reference, 0); } return new AssemblyReferenceBinding(reference); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { using MetadataOrDiagnostic = System.Object; /// <summary> /// The base class for language specific assembly managers. /// </summary> /// <typeparam name="TCompilation">Language specific representation for a compilation</typeparam> /// <typeparam name="TAssemblySymbol">Language specific representation for an assembly symbol.</typeparam> internal abstract partial class CommonReferenceManager<TCompilation, TAssemblySymbol> where TCompilation : Compilation where TAssemblySymbol : class, IAssemblySymbolInternal { protected abstract CommonMessageProvider MessageProvider { get; } protected abstract AssemblyData CreateAssemblyDataForFile( PEAssembly assembly, WeakList<IAssemblySymbolInternal> cachedSymbols, DocumentationProvider documentationProvider, string sourceAssemblySimpleName, MetadataImportOptions importOptions, bool embedInteropTypes); protected abstract AssemblyData CreateAssemblyDataForCompilation( CompilationReference compilationReference); /// <summary> /// Checks if the properties of <paramref name="duplicateReference"/> are compatible with properties of <paramref name="primaryReference"/>. /// Reports inconsistencies to the given diagnostic bag. /// </summary> /// <returns>True if the properties are compatible and hence merged, false if the duplicate reference should not merge it's properties with primary reference.</returns> protected abstract bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics); /// <summary> /// Called to compare two weakly named identities with the same name. /// </summary> protected abstract bool WeakIdentityPropertiesEquivalent(AssemblyIdentity identity1, AssemblyIdentity identity2); [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] protected struct ResolvedReference { private readonly MetadataImageKind _kind; private readonly int _index; private readonly ImmutableArray<string> _aliasesOpt; private readonly ImmutableArray<string> _recursiveAliasesOpt; private readonly ImmutableArray<MetadataReference> _mergedReferencesOpt; // uninitialized aliases public ResolvedReference(int index, MetadataImageKind kind) { Debug.Assert(index >= 0); _index = index + 1; _kind = kind; _aliasesOpt = default(ImmutableArray<string>); _recursiveAliasesOpt = default(ImmutableArray<string>); _mergedReferencesOpt = default(ImmutableArray<MetadataReference>); } // initialized aliases public ResolvedReference(int index, MetadataImageKind kind, ImmutableArray<string> aliasesOpt, ImmutableArray<string> recursiveAliasesOpt, ImmutableArray<MetadataReference> mergedReferences) : this(index, kind) { // We have to have non-default aliases (empty are ok). We can have both recursive and non-recursive aliases if two references were merged. Debug.Assert(!aliasesOpt.IsDefault || !recursiveAliasesOpt.IsDefault); Debug.Assert(!mergedReferences.IsDefault); _aliasesOpt = aliasesOpt; _recursiveAliasesOpt = recursiveAliasesOpt; _mergedReferencesOpt = mergedReferences; } private bool IsUninitialized => (_aliasesOpt.IsDefault && _recursiveAliasesOpt.IsDefault) || _mergedReferencesOpt.IsDefault; /// <summary> /// Aliases that should be applied to the referenced assembly. /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification). /// Null if not applicable (the reference only has recursive aliases). /// </summary> public ImmutableArray<string> AliasesOpt { get { Debug.Assert(!IsUninitialized); return _aliasesOpt; } } /// <summary> /// Aliases that should be applied recursively to all dependent assemblies. /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification). /// Null if not applicable (the reference only has simple aliases). /// </summary> public ImmutableArray<string> RecursiveAliasesOpt { get { Debug.Assert(!IsUninitialized); return _recursiveAliasesOpt; } } public ImmutableArray<MetadataReference> MergedReferences { get { Debug.Assert(!IsUninitialized); return _mergedReferencesOpt; } } /// <summary> /// default(<see cref="ResolvedReference"/>) is considered skipped. /// </summary> public bool IsSkipped { get { return _index == 0; } } public MetadataImageKind Kind { get { Debug.Assert(!IsSkipped); return _kind; } } /// <summary> /// Index into an array of assemblies (not including the assembly being built) or an array of modules, depending on <see cref="Kind"/>. /// </summary> public int Index { get { Debug.Assert(!IsSkipped); return _index - 1; } } private string GetDebuggerDisplay() { return IsSkipped ? "<skipped>" : $"{(_kind == MetadataImageKind.Assembly ? "A" : "M")}[{Index}]:{DisplayAliases(_aliasesOpt, "aliases")}{DisplayAliases(_recursiveAliasesOpt, "recursive-aliases")}"; } private static string DisplayAliases(ImmutableArray<string> aliasesOpt, string name) { return aliasesOpt.IsDefault ? "" : $" {name} = '{string.Join("','", aliasesOpt)}'"; } } protected readonly struct ReferencedAssemblyIdentity { public readonly AssemblyIdentity? Identity; public readonly MetadataReference? Reference; /// <summary> /// non-negative: Index into the array of all (explicitly and implicitly) referenced assemblies. /// negative: ExplicitlyReferencedAssemblies.Count + RelativeAssemblyIndex is an index into the array of assemblies. /// </summary> public readonly int RelativeAssemblyIndex; public int GetAssemblyIndex(int explicitlyReferencedAssemblyCount) => RelativeAssemblyIndex >= 0 ? RelativeAssemblyIndex : explicitlyReferencedAssemblyCount + RelativeAssemblyIndex; public ReferencedAssemblyIdentity(AssemblyIdentity identity, MetadataReference reference, int relativeAssemblyIndex) { Identity = identity; Reference = reference; RelativeAssemblyIndex = relativeAssemblyIndex; } } /// <summary> /// Resolves given metadata references to assemblies and modules. /// </summary> /// <param name="compilation">The compilation whose references are being resolved.</param> /// <param name="assemblyReferencesBySimpleName"> /// Used to filter out assemblies that have the same strong or weak identity. /// Maps simple name to a list of identities. The highest version of each name is the first. /// </param> /// <param name="references">List where to store resolved references. References from #r directives will follow references passed to the compilation constructor.</param> /// <param name="boundReferenceDirectiveMap">Maps #r values to successfully resolved metadata references. Does not contain values that failed to resolve.</param> /// <param name="boundReferenceDirectives">Unique metadata references resolved from #r directives.</param> /// <param name="assemblies">List where to store information about resolved assemblies to.</param> /// <param name="modules">List where to store information about resolved modules to.</param> /// <param name="diagnostics">Diagnostic bag where to report resolution errors.</param> /// <returns> /// Maps index to <paramref name="references"/> to an index of a resolved assembly or module in <paramref name="assemblies"/> or <paramref name="modules"/>, respectively. ///</returns> protected ImmutableArray<ResolvedReference> ResolveMetadataReferences( TCompilation compilation, [Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName, out ImmutableArray<MetadataReference> references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectiveMap, out ImmutableArray<MetadataReference> boundReferenceDirectives, out ImmutableArray<AssemblyData> assemblies, out ImmutableArray<PEModule> modules, DiagnosticBag diagnostics) { // Locations of all #r directives in the order they are listed in the references list. ImmutableArray<Location> referenceDirectiveLocations; GetCompilationReferences(compilation, diagnostics, out references, out boundReferenceDirectiveMap, out referenceDirectiveLocations); // References originating from #r directives precede references supplied as arguments of the compilation. int referenceCount = references.Length; int referenceDirectiveCount = (referenceDirectiveLocations != null ? referenceDirectiveLocations.Length : 0); var referenceMap = new ResolvedReference[referenceCount]; // Maps references that were added to the reference set (i.e. not filtered out as duplicates) to a set of names that // can be used to alias these references. Duplicate assemblies contribute their aliases into this set. Dictionary<MetadataReference, MergedAliases>? lazyAliasMap = null; // Used to filter out duplicate references that reference the same file (resolve to the same full normalized path). var boundReferences = new Dictionary<MetadataReference, MetadataReference>(MetadataReferenceEqualityComparer.Instance); ArrayBuilder<MetadataReference>? uniqueDirectiveReferences = (referenceDirectiveLocations != null) ? ArrayBuilder<MetadataReference>.GetInstance() : null; var assembliesBuilder = ArrayBuilder<AssemblyData>.GetInstance(); ArrayBuilder<PEModule>? lazyModulesBuilder = null; bool supersedeLowerVersions = compilation.Options.ReferencesSupersedeLowerVersions; // When duplicate references with conflicting EmbedInteropTypes flag are encountered, // VB uses the flag from the last one, C# reports an error. We need to enumerate in reverse order // so that we find the one that matters first. for (int referenceIndex = referenceCount - 1; referenceIndex >= 0; referenceIndex--) { var boundReference = references[referenceIndex]; if (boundReference == null) { continue; } // add bound reference if it doesn't exist yet, merging aliases: MetadataReference? existingReference; if (boundReferences.TryGetValue(boundReference, out existingReference)) { // merge properties of compilation-based references if the underlying compilations are the same if ((object)boundReference != existingReference) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); } continue; } boundReferences.Add(boundReference, boundReference); Location location; if (referenceIndex < referenceDirectiveCount) { location = referenceDirectiveLocations[referenceIndex]; uniqueDirectiveReferences!.Add(boundReference); } else { location = Location.None; } // compilation reference var compilationReference = boundReference as CompilationReference; if (compilationReference != null) { switch (compilationReference.Properties.Kind) { case MetadataImageKind.Assembly: existingReference = TryAddAssembly( compilationReference.Compilation.Assembly.Identity, boundReference, -assembliesBuilder.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, supersedeLowerVersions); if (existingReference != null) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); continue; } // Note, if SourceAssemblySymbol hasn't been created for // compilationAssembly.Compilation yet, we want this to happen // right now. Conveniently, this constructor will trigger creation of the // SourceAssemblySymbol. var asmData = CreateAssemblyDataForCompilation(compilationReference); AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder); break; default: throw ExceptionUtilities.UnexpectedValue(compilationReference.Properties.Kind); } continue; } // PE reference var peReference = (PortableExecutableReference)boundReference; Metadata? metadata = GetMetadata(peReference, MessageProvider, location, diagnostics); Debug.Assert(metadata != null || diagnostics.HasAnyErrors()); if (metadata != null) { switch (peReference.Properties.Kind) { case MetadataImageKind.Assembly: var assemblyMetadata = (AssemblyMetadata)metadata; WeakList<IAssemblySymbolInternal> cachedSymbols = assemblyMetadata.CachedSymbols; if (assemblyMetadata.IsValidAssembly()) { PEAssembly? assembly = assemblyMetadata.GetAssembly(); Debug.Assert(assembly is object); existingReference = TryAddAssembly( assembly.Identity, peReference, -assembliesBuilder.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, supersedeLowerVersions); if (existingReference != null) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); continue; } var asmData = CreateAssemblyDataForFile( assembly, cachedSymbols, peReference.DocumentationProvider, SimpleAssemblyName, compilation.Options.MetadataImportOptions, peReference.Properties.EmbedInteropTypes); AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder); } else { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, location, peReference.Display ?? "")); } // asmData keeps strong ref after this point GC.KeepAlive(assemblyMetadata); break; case MetadataImageKind.Module: var moduleMetadata = (ModuleMetadata)metadata; if (moduleMetadata.Module.IsLinkedModule) { // We don't support netmodules since some checks in the compiler need information from the full PE image // (Machine, Bit32Required, PE image hash). if (!moduleMetadata.Module.IsEntireImageAvailable) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage, location, peReference.Display ?? "")); } AddModule(moduleMetadata.Module, referenceIndex, referenceMap, ref lazyModulesBuilder); } else { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotModule, location, peReference.Display ?? "")); } break; default: throw ExceptionUtilities.UnexpectedValue(peReference.Properties.Kind); } } } if (uniqueDirectiveReferences != null) { uniqueDirectiveReferences.ReverseContents(); boundReferenceDirectives = uniqueDirectiveReferences.ToImmutableAndFree(); } else { boundReferenceDirectives = ImmutableArray<MetadataReference>.Empty; } // We enumerated references in reverse order in the above code // and thus assemblies and modules in the builders are reversed. // Fix up all the indices and reverse the builder content now to get // the ordering matching the references. // // Also fills in aliases. for (int i = 0; i < referenceMap.Length; i++) { if (!referenceMap[i].IsSkipped) { int count = (referenceMap[i].Kind == MetadataImageKind.Assembly) ? assembliesBuilder.Count : lazyModulesBuilder?.Count ?? 0; int reversedIndex = count - 1 - referenceMap[i].Index; referenceMap[i] = GetResolvedReferenceAndFreePropertyMapEntry(references[i], reversedIndex, referenceMap[i].Kind, lazyAliasMap); } } assembliesBuilder.ReverseContents(); assemblies = assembliesBuilder.ToImmutableAndFree(); if (lazyModulesBuilder == null) { modules = ImmutableArray<PEModule>.Empty; } else { lazyModulesBuilder.ReverseContents(); modules = lazyModulesBuilder.ToImmutableAndFree(); } return ImmutableArray.CreateRange(referenceMap); } private static ResolvedReference GetResolvedReferenceAndFreePropertyMapEntry(MetadataReference reference, int index, MetadataImageKind kind, Dictionary<MetadataReference, MergedAliases>? propertyMapOpt) { ImmutableArray<string> aliasesOpt, recursiveAliasesOpt; var mergedReferences = ImmutableArray<MetadataReference>.Empty; if (propertyMapOpt != null && propertyMapOpt.TryGetValue(reference, out MergedAliases? mergedProperties)) { aliasesOpt = mergedProperties.AliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>); recursiveAliasesOpt = mergedProperties.RecursiveAliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>); if (mergedProperties.MergedReferencesOpt is object) { mergedReferences = mergedProperties.MergedReferencesOpt.ToImmutableAndFree(); } } else if (reference.Properties.HasRecursiveAliases) { aliasesOpt = default(ImmutableArray<string>); recursiveAliasesOpt = reference.Properties.Aliases; } else { aliasesOpt = reference.Properties.Aliases; recursiveAliasesOpt = default(ImmutableArray<string>); } return new ResolvedReference(index, kind, aliasesOpt, recursiveAliasesOpt, mergedReferences); } /// <summary> /// Creates or gets metadata for PE reference. /// </summary> /// <remarks> /// If any of the following exceptions: <see cref="BadImageFormatException"/>, <see cref="FileNotFoundException"/>, <see cref="IOException"/>, /// are thrown while reading the metadata file, the exception is caught and an appropriate diagnostic stored in <paramref name="diagnostics"/>. /// </remarks> private Metadata? GetMetadata(PortableExecutableReference peReference, CommonMessageProvider messageProvider, Location location, DiagnosticBag diagnostics) { Metadata? existingMetadata; lock (ObservedMetadata) { if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata)) { return existingMetadata; } } Metadata? newMetadata; Diagnostic? newDiagnostic = null; try { newMetadata = peReference.GetMetadataNoCopy(); // make sure basic structure of the PE image is valid: if (newMetadata is AssemblyMetadata assemblyMetadata) { _ = assemblyMetadata.IsValidAssembly(); } else { _ = ((ModuleMetadata)newMetadata).Module.IsLinkedModule; } } catch (Exception e) when (e is BadImageFormatException || e is IOException) { newDiagnostic = PortableExecutableReference.ExceptionToDiagnostic(e, messageProvider, location, peReference.Display ?? "", peReference.Properties.Kind); newMetadata = null; } lock (ObservedMetadata) { if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata)) { return existingMetadata; } if (newDiagnostic != null) { diagnostics.Add(newDiagnostic); } ObservedMetadata.Add(peReference, (MetadataOrDiagnostic?)newMetadata ?? newDiagnostic!); return newMetadata; } } private bool TryGetObservedMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics, out Metadata? metadata) { if (ObservedMetadata.TryGetValue(peReference, out MetadataOrDiagnostic? existing)) { Debug.Assert(existing is Metadata || existing is Diagnostic); metadata = existing as Metadata; if (metadata == null) { diagnostics.Add((Diagnostic)existing); } return true; } metadata = null; return false; } internal AssemblyMetadata? GetAssemblyMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics) { var metadata = GetMetadata(peReference, MessageProvider, Location.None, diagnostics); Debug.Assert(metadata != null || diagnostics.HasAnyErrors()); if (metadata == null) { return null; } // require the metadata to be a valid assembly metadata: var assemblyMetadata = metadata as AssemblyMetadata; if (assemblyMetadata?.IsValidAssembly() != true) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, Location.None, peReference.Display ?? "")); return null; } return assemblyMetadata; } /// <summary> /// Determines whether references are the same. Compilation references are the same if they refer to the same compilation. /// Otherwise, references are represented by their object identities. /// </summary> internal sealed class MetadataReferenceEqualityComparer : IEqualityComparer<MetadataReference> { internal static readonly MetadataReferenceEqualityComparer Instance = new MetadataReferenceEqualityComparer(); public bool Equals(MetadataReference? x, MetadataReference? y) { if (ReferenceEquals(x, y)) { return true; } var cx = x as CompilationReference; if (cx != null) { var cy = y as CompilationReference; if (cy != null) { return (object)cx.Compilation == cy.Compilation; } } return false; } public int GetHashCode(MetadataReference reference) { var compilationReference = reference as CompilationReference; if (compilationReference != null) { return RuntimeHelpers.GetHashCode(compilationReference.Compilation); } return RuntimeHelpers.GetHashCode(reference); } } /// <summary> /// Merges aliases of the first observed reference (<paramref name="primaryReference"/>) with aliases specified for an equivalent reference (<paramref name="newReference"/>). /// Empty alias list is considered to be the same as a list containing "global", since in both cases C# allows unqualified access to the symbols. /// </summary> private void MergeReferenceProperties(MetadataReference primaryReference, MetadataReference newReference, DiagnosticBag diagnostics, ref Dictionary<MetadataReference, MergedAliases>? lazyAliasMap) { if (!CheckPropertiesConsistency(newReference, primaryReference, diagnostics)) { return; } if (lazyAliasMap == null) { lazyAliasMap = new Dictionary<MetadataReference, MergedAliases>(); } MergedAliases? mergedAliases; if (!lazyAliasMap.TryGetValue(primaryReference, out mergedAliases)) { mergedAliases = new MergedAliases(); lazyAliasMap.Add(primaryReference, mergedAliases); mergedAliases.Merge(primaryReference); } mergedAliases.Merge(newReference); } /// <remarks> /// Caller is responsible for freeing any allocated ArrayBuilders. /// </remarks> private static void AddAssembly(AssemblyData data, int referenceIndex, ResolvedReference[] referenceMap, ArrayBuilder<AssemblyData> assemblies) { // aliases will be filled in later: referenceMap[referenceIndex] = new ResolvedReference(assemblies.Count, MetadataImageKind.Assembly); assemblies.Add(data); } /// <remarks> /// Caller is responsible for freeing any allocated ArrayBuilders. /// </remarks> private static void AddModule(PEModule module, int referenceIndex, ResolvedReference[] referenceMap, [NotNull] ref ArrayBuilder<PEModule>? modules) { if (modules == null) { modules = ArrayBuilder<PEModule>.GetInstance(); } referenceMap[referenceIndex] = new ResolvedReference(modules.Count, MetadataImageKind.Module); modules.Add(module); } /// <summary> /// Returns null if an assembly of an equivalent identity has not been added previously, otherwise returns the reference that added it. /// Two identities are considered equivalent if /// - both assembly names are strong (have keys) and are either equal or FX unified /// - both assembly names are weak (no keys) and have the same simple name. /// </summary> private MetadataReference? TryAddAssembly( AssemblyIdentity identity, MetadataReference reference, int assemblyIndex, DiagnosticBag diagnostics, Location location, Dictionary<string, List<ReferencedAssemblyIdentity>> referencesBySimpleName, bool supersedeLowerVersions) { var referencedAssembly = new ReferencedAssemblyIdentity(identity, reference, assemblyIndex); List<ReferencedAssemblyIdentity>? sameSimpleNameIdentities; if (!referencesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities)) { referencesBySimpleName.Add(identity.Name, new List<ReferencedAssemblyIdentity> { referencedAssembly }); return null; } if (supersedeLowerVersions) { foreach (var other in sameSimpleNameIdentities) { Debug.Assert(other.Identity is object); if (identity.Version == other.Identity.Version) { return other.Reference; } } // Keep all versions of the assembly and the first identity in the list the one with the highest version: if (sameSimpleNameIdentities[0].Identity!.Version > identity.Version) { sameSimpleNameIdentities.Add(referencedAssembly); } else { sameSimpleNameIdentities.Add(sameSimpleNameIdentities[0]); sameSimpleNameIdentities[0] = referencedAssembly; } return null; } ReferencedAssemblyIdentity equivalent = default(ReferencedAssemblyIdentity); if (identity.IsStrongName) { foreach (var other in sameSimpleNameIdentities) { // Only compare strong with strong (weak is never equivalent to strong and vice versa). // In order to eliminate duplicate references we need to try to match their identities in both directions since // ReferenceMatchesDefinition is not necessarily symmetric. // (e.g. System.Numerics.Vectors, Version=4.1+ matches System.Numerics.Vectors, Version=4.0, but not the other way around.) Debug.Assert(other.Identity is object); if (other.Identity.IsStrongName && IdentityComparer.ReferenceMatchesDefinition(identity, other.Identity) && IdentityComparer.ReferenceMatchesDefinition(other.Identity, identity)) { equivalent = other; break; } } } else { foreach (var other in sameSimpleNameIdentities) { // only compare weak with weak Debug.Assert(other.Identity is object); if (!other.Identity.IsStrongName && WeakIdentityPropertiesEquivalent(identity, other.Identity)) { equivalent = other; break; } } } if (equivalent.Identity == null) { sameSimpleNameIdentities.Add(referencedAssembly); return null; } // equivalent found - ignore and/or report an error: if (identity.IsStrongName) { Debug.Assert(equivalent.Identity.IsStrongName); // versions might have been unified for a Framework assembly: if (identity != equivalent.Identity) { // Dev12 C# reports an error // Dev12 VB keeps both references in the compilation and reports an ambiguity error when a symbol is used. // BREAKING CHANGE in VB: we report an error for both languages // Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references. MessageProvider.ReportDuplicateMetadataReferenceStrong(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity); } // If the versions match exactly we ignore duplicates w/o reporting errors while // Dev12 C# reports: // error CS1703: An assembly with the same identity '{0}' has already been imported. Try removing one of the duplicate references. // Dev12 VB reports: // Fatal error BC2000 : compiler initialization failed unexpectedly: Project already has a reference to assembly System. // A second reference to 'D:\Temp\System.dll' cannot be added. } else { Debug.Assert(!equivalent.Identity.IsStrongName); // Dev12 reports an error for all weak-named assemblies, even if the versions are the same. // We treat assemblies with the same name and version equal even if they don't have a strong name. // This change allows us to de-duplicate #r references based on identities rather than full paths, // and is closer to platforms that don't support strong names and consider name and version enough // to identify an assembly. An identity without version is considered to have version 0.0.0.0. if (identity != equivalent.Identity) { MessageProvider.ReportDuplicateMetadataReferenceWeak(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity); } } Debug.Assert(equivalent.Reference != null); return equivalent.Reference; } protected void GetCompilationReferences( TCompilation compilation, DiagnosticBag diagnostics, out ImmutableArray<MetadataReference> references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectives, out ImmutableArray<Location> referenceDirectiveLocations) { ArrayBuilder<MetadataReference> referencesBuilder = ArrayBuilder<MetadataReference>.GetInstance(); ArrayBuilder<Location>? referenceDirectiveLocationsBuilder = null; IDictionary<(string, string), MetadataReference>? localBoundReferenceDirectives = null; try { foreach (var referenceDirective in compilation.ReferenceDirectives) { Debug.Assert(referenceDirective.Location is object); if (compilation.Options.MetadataReferenceResolver == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataReferencesNotSupported, referenceDirective.Location)); break; } // we already successfully bound #r with the same value: Debug.Assert(referenceDirective.File is object); Debug.Assert(referenceDirective.Location.SourceTree is object); if (localBoundReferenceDirectives != null && localBoundReferenceDirectives.ContainsKey((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 (localBoundReferenceDirectives == null) { localBoundReferenceDirectives = new Dictionary<(string, string), MetadataReference>(); referenceDirectiveLocationsBuilder = ArrayBuilder<Location>.GetInstance(); } referencesBuilder.Add(boundReference); referenceDirectiveLocationsBuilder!.Add(referenceDirective.Location); localBoundReferenceDirectives.Add((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 (localBoundReferenceDirectives == null) { // no directive references resolved successfully: localBoundReferenceDirectives = SpecializedCollections.EmptyDictionary<(string, string), MetadataReference>(); } boundReferenceDirectives = localBoundReferenceDirectives; 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(); } } /// <summary> /// For each given directive return a bound PE reference, or null if the binding fails. /// </summary> private static PortableExecutableReference? ResolveReferenceDirective(string reference, Location location, TCompilation compilation) { var tree = location.SourceTree; string? basePath = (tree != null && tree.FilePath.Length > 0) ? tree.FilePath : null; // checked earlier: Debug.Assert(compilation.Options.MetadataReferenceResolver != null); var references = compilation.Options.MetadataReferenceResolver.ResolveReference(reference, basePath, MetadataReferenceProperties.Assembly.WithRecursiveAliases(true)); if (references.IsDefaultOrEmpty) { return null; } if (references.Length > 1) { // TODO: implement throw new NotSupportedException(); } return references[0]; } internal static AssemblyReferenceBinding[] ResolveReferencedAssemblies( ImmutableArray<AssemblyIdentity> references, ImmutableArray<AssemblyData> definitions, int definitionStartIndex, AssemblyIdentityComparer assemblyIdentityComparer) { var boundReferences = new AssemblyReferenceBinding[references.Length]; for (int j = 0; j < references.Length; j++) { boundReferences[j] = ResolveReferencedAssembly(references[j], definitions, definitionStartIndex, assemblyIdentityComparer); } return boundReferences; } /// <summary> /// Used to match AssemblyRef with AssemblyDef. /// </summary> /// <param name="definitions">Array of definition identities to match against.</param> /// <param name="definitionStartIndex">An index of the first definition to consider, <paramref name="definitions"/> preceding this index are ignored.</param> /// <param name="reference">Reference identity to resolve.</param> /// <param name="assemblyIdentityComparer">Assembly identity comparer.</param> /// <returns> /// Returns an index the reference is bound. /// </returns> internal static AssemblyReferenceBinding ResolveReferencedAssembly( AssemblyIdentity reference, ImmutableArray<AssemblyData> definitions, int definitionStartIndex, AssemblyIdentityComparer assemblyIdentityComparer) { // Dev11 C# compiler allows the versions to not match exactly, assuming that a newer library may be used instead of an older version. // For a given reference it finds a definition with the lowest version that is higher then or equal to the reference version. // If match.Version != reference.Version a warning is reported. // definition with the lowest version higher than reference version, unless exact version found int minHigherVersionDefinition = -1; int maxLowerVersionDefinition = -1; // Skip assembly being built for now; it will be considered at the very end: bool resolveAgainstAssemblyBeingBuilt = definitionStartIndex == 0; definitionStartIndex = Math.Max(definitionStartIndex, 1); for (int i = definitionStartIndex; i < definitions.Length; i++) { AssemblyIdentity definition = definitions[i].Identity; switch (assemblyIdentityComparer.Compare(reference, definition)) { case AssemblyIdentityComparer.ComparisonResult.NotEquivalent: continue; case AssemblyIdentityComparer.ComparisonResult.Equivalent: return new AssemblyReferenceBinding(reference, i); case AssemblyIdentityComparer.ComparisonResult.EquivalentIgnoringVersion: if (reference.Version < definition.Version) { // Refers to an older assembly than we have if (minHigherVersionDefinition == -1 || definition.Version < definitions[minHigherVersionDefinition].Identity.Version) { minHigherVersionDefinition = i; } } else { Debug.Assert(reference.Version > definition.Version); // Refers to a newer assembly than we have if (maxLowerVersionDefinition == -1 || definition.Version > definitions[maxLowerVersionDefinition].Identity.Version) { maxLowerVersionDefinition = i; } } continue; default: throw ExceptionUtilities.Unreachable; } } // we haven't found definition that matches the reference if (minHigherVersionDefinition != -1) { return new AssemblyReferenceBinding(reference, minHigherVersionDefinition, versionDifference: +1); } if (maxLowerVersionDefinition != -1) { return new AssemblyReferenceBinding(reference, maxLowerVersionDefinition, versionDifference: -1); } // Handle cases where Windows.winmd is a runtime substitute for a // reference to a compile-time winmd. This is for scenarios such as a // debugger EE which constructs a compilation from the modules of // the running process where Windows.winmd loaded at runtime is a // substitute for a collection of Windows.*.winmd compile-time references. if (reference.IsWindowsComponent()) { for (int i = definitionStartIndex; i < definitions.Length; i++) { if (definitions[i].Identity.IsWindowsRuntime()) { return new AssemblyReferenceBinding(reference, i); } } } // In the IDE it is possible the reference we're looking for is a // compilation reference to a source assembly. However, if the reference // is of ContentType WindowsRuntime then the compilation will never // match since all C#/VB WindowsRuntime compilations output .winmdobjs, // not .winmds, and the ContentType of a .winmdobj is Default. // If this is the case, we want to ignore the ContentType mismatch and // allow the compilation to match the reference. if (reference.ContentType == AssemblyContentType.WindowsRuntime) { for (int i = definitionStartIndex; i < definitions.Length; i++) { var definition = definitions[i].Identity; var sourceCompilation = definitions[i].SourceCompilation; if (definition.ContentType == AssemblyContentType.Default && sourceCompilation?.Options.OutputKind == OutputKind.WindowsRuntimeMetadata && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definition.Name) && reference.Version.Equals(definition.Version) && reference.IsRetargetable == definition.IsRetargetable && AssemblyIdentityComparer.CultureComparer.Equals(reference.CultureName, definition.CultureName) && AssemblyIdentity.KeysEqual(reference, definition)) { return new AssemblyReferenceBinding(reference, i); } } } // As in the native compiler (see IMPORTER::MapAssemblyRefToAid), we compare against the // compilation (i.e. source) assembly as a last resort. We follow the native approach of // skipping the public key comparison since we have yet to compute it. if (resolveAgainstAssemblyBeingBuilt && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definitions[0].Identity.Name)) { Debug.Assert(definitions[0].Identity.PublicKeyToken.IsEmpty); return new AssemblyReferenceBinding(reference, 0); } return new AssemblyReferenceBinding(reference); } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/EditorFeatures/Test/DocCommentFormatting/DocCommentFormattingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.VisualBasic.DocumentationComments; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.DocCommentFormatting { public class DocCommentFormattingTests { private readonly CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService(); private readonly VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService(); private void TestFormat(string xmlFragment, string expectedCSharp, string expectedVB) { var csharpFormattedText = _csharpService.Format(xmlFragment); var vbFormattedText = _vbService.Format(xmlFragment); Assert.Equal(expectedCSharp, csharpFormattedText); Assert.Equal(expectedVB, vbFormattedText); } private void TestFormat(string xmlFragment, string expected) => TestFormat(xmlFragment, expected, expected); [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void CTag() { var comment = "Class <c>Point</c> models a point in a two-dimensional plane."; var expected = "Class Point models a point in a two-dimensional plane."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ExampleAndCodeTags() { var comment = @"This method changes the point's location by the given x- and y-offsets. <example>For example: <code> Point p = new Point(3,5); p.Translate(-1,3); </code> results in <c>p</c>'s having the value (2,8). </example>"; var expected = "This method changes the point's location by the given x- and y-offsets. For example:\r\n\r\n Point p = new Point(3,5);\r\n p.Translate(-1,3);\r\n \r\n\r\nresults in p's having the value (2,8)."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ListTag() { var comment = @"Here is an example of a bulleted list: <list type=""bullet""> <item> <description>Item 1.</description> </item> <item> <description>Item 2.</description> </item> </list>"; var expected = "Here is an example of a bulleted list:\r\n\r\n• Item 1.\r\n• Item 2."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ParaTag() { var comment = @"This is the entry point of the Point class testing program. <para>This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class.</para>"; var expected = @"This is the entry point of the Point class testing program. This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestPermissionTag() { var comment = @"<permission cref=""System.Security.PermissionSet"">Everyone can access this method.</permission>"; var expected = @"Everyone can access this method."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeTag() { var comment = @"<see cref=""AnotherFunction""/>"; var expected = @"AnotherFunction"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlsoTag() { var comment = @"<seealso cref=""AnotherFunction""/>"; var expected = @"AnotherFunction"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ValueTag() { var comment = @"<value>Property <c>X</c> represents the point's x-coordinate.</value>"; var expected = @"Property X represents the point's x-coordinate."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestParamRefTag() { var comment = @"This constructor initializes the new Point to (<paramref name=""xor""/>,<paramref name=""yor""/>)."; var expected = "This constructor initializes the new Point to (xor,yor)."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestTypeParamRefTag() { var comment = @"This method fetches data and returns a list of <typeparamref name=""Z""/>."; var expected = @"This method fetches data and returns a list of Z."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace1() { var comment = " This has extra whitespace. "; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace2() { var comment = @" This has extra whitespace. "; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace3() { var comment = "This has extra whitespace."; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs1() { var comment = @" <para>This is part of a paragraph.</para> "; var expected = "This is part of a paragraph."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs2() { var comment = @" <para>This is part of a paragraph.</para> <para>This is also part of a paragraph.</para> "; var expected = @"This is part of a paragraph. This is also part of a paragraph."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs3() { var comment = @" This is a summary. <para>This is part of a paragraph.</para> "; var expected = @"This is a summary. This is part of a paragraph."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs4() { var comment = @" <para>This is part of a paragraph.</para> This is part of the summary, too. "; var expected = @"This is part of a paragraph. This is part of the summary, too."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] [WorkItem(32838, "https://github.com/dotnet/roslyn/issues/32838")] public void Paragraphs5() { var comment = @" <para>This is part of a<br/>paragraph.</para> <para>This is also part of a paragraph.</para> "; var expected = @"This is part of a paragraph. This is also part of a paragraph."; TestFormat(comment, expected); } [Theory, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] [InlineData("<br/><br/>")] [InlineData("<br/><br/><br/>")] [WorkItem(32838, "https://github.com/dotnet/roslyn/issues/32838")] public void Paragraphs6(string lineBreak) { var comment = $@" <para>This is part of a{lineBreak}paragraph.</para> <para>This is also part of a paragraph.</para> "; var expected = @"This is part of a paragraph. This is also part of a paragraph."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See1() { var comment = @"See <see cref=""T:System.Object"" />"; var expected = "See System.Object"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See2() { var comment = @"See <see />"; var expected = @"See"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See3() { var comment = @"See <see langword=""true"" />"; var expected = "See true"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See4() { var comment = @"See <see href=""https://github.com"" />"; var expected = "See https://github.com"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See5() { var comment = @"See <see href=""https://github.com"">GitHub</see>"; var expected = "See GitHub"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See6() { var comment = @"See <see href=""https://github.com""></see>"; var expected = "See https://github.com"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso1() { var comment = @"See also <seealso cref=""T:System.Object"" />"; var expected = @"See also System.Object"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso2() { var comment = @"See also <seealso />"; var expected = @"See also"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso3() { var comment = @"See also <seealso langword=""true"" />"; var expected = "See also true"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso4() { var comment = @"See also <seealso href=""https://github.com"" />"; var expected = "See also https://github.com"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso5() { var comment = @"See also <seealso href=""https://github.com"">GitHub</seealso>"; var expected = "See also GitHub"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso6() { var comment = @"See also <seealso href=""https://github.com""></seealso>"; var expected = "See also https://github.com"; TestFormat(comment, expected); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.VisualBasic.DocumentationComments; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.DocCommentFormatting { public class DocCommentFormattingTests { private readonly CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService(); private readonly VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService(); private void TestFormat(string xmlFragment, string expectedCSharp, string expectedVB) { var csharpFormattedText = _csharpService.Format(xmlFragment); var vbFormattedText = _vbService.Format(xmlFragment); Assert.Equal(expectedCSharp, csharpFormattedText); Assert.Equal(expectedVB, vbFormattedText); } private void TestFormat(string xmlFragment, string expected) => TestFormat(xmlFragment, expected, expected); [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void CTag() { var comment = "Class <c>Point</c> models a point in a two-dimensional plane."; var expected = "Class Point models a point in a two-dimensional plane."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ExampleAndCodeTags() { var comment = @"This method changes the point's location by the given x- and y-offsets. <example>For example: <code> Point p = new Point(3,5); p.Translate(-1,3); </code> results in <c>p</c>'s having the value (2,8). </example>"; var expected = "This method changes the point's location by the given x- and y-offsets. For example:\r\n\r\n Point p = new Point(3,5);\r\n p.Translate(-1,3);\r\n \r\n\r\nresults in p's having the value (2,8)."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ListTag() { var comment = @"Here is an example of a bulleted list: <list type=""bullet""> <item> <description>Item 1.</description> </item> <item> <description>Item 2.</description> </item> </list>"; var expected = "Here is an example of a bulleted list:\r\n\r\n• Item 1.\r\n• Item 2."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ParaTag() { var comment = @"This is the entry point of the Point class testing program. <para>This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class.</para>"; var expected = @"This is the entry point of the Point class testing program. This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestPermissionTag() { var comment = @"<permission cref=""System.Security.PermissionSet"">Everyone can access this method.</permission>"; var expected = @"Everyone can access this method."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeTag() { var comment = @"<see cref=""AnotherFunction""/>"; var expected = @"AnotherFunction"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlsoTag() { var comment = @"<seealso cref=""AnotherFunction""/>"; var expected = @"AnotherFunction"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ValueTag() { var comment = @"<value>Property <c>X</c> represents the point's x-coordinate.</value>"; var expected = @"Property X represents the point's x-coordinate."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestParamRefTag() { var comment = @"This constructor initializes the new Point to (<paramref name=""xor""/>,<paramref name=""yor""/>)."; var expected = "This constructor initializes the new Point to (xor,yor)."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestTypeParamRefTag() { var comment = @"This method fetches data and returns a list of <typeparamref name=""Z""/>."; var expected = @"This method fetches data and returns a list of Z."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace1() { var comment = " This has extra whitespace. "; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace2() { var comment = @" This has extra whitespace. "; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace3() { var comment = "This has extra whitespace."; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs1() { var comment = @" <para>This is part of a paragraph.</para> "; var expected = "This is part of a paragraph."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs2() { var comment = @" <para>This is part of a paragraph.</para> <para>This is also part of a paragraph.</para> "; var expected = @"This is part of a paragraph. This is also part of a paragraph."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs3() { var comment = @" This is a summary. <para>This is part of a paragraph.</para> "; var expected = @"This is a summary. This is part of a paragraph."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs4() { var comment = @" <para>This is part of a paragraph.</para> This is part of the summary, too. "; var expected = @"This is part of a paragraph. This is part of the summary, too."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] [WorkItem(32838, "https://github.com/dotnet/roslyn/issues/32838")] public void Paragraphs5() { var comment = @" <para>This is part of a<br/>paragraph.</para> <para>This is also part of a paragraph.</para> "; var expected = @"This is part of a paragraph. This is also part of a paragraph."; TestFormat(comment, expected); } [Theory, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] [InlineData("<br/><br/>")] [InlineData("<br/><br/><br/>")] [WorkItem(32838, "https://github.com/dotnet/roslyn/issues/32838")] public void Paragraphs6(string lineBreak) { var comment = $@" <para>This is part of a{lineBreak}paragraph.</para> <para>This is also part of a paragraph.</para> "; var expected = @"This is part of a paragraph. This is also part of a paragraph."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See1() { var comment = @"See <see cref=""T:System.Object"" />"; var expected = "See System.Object"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See2() { var comment = @"See <see />"; var expected = @"See"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See3() { var comment = @"See <see langword=""true"" />"; var expected = "See true"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See4() { var comment = @"See <see href=""https://github.com"" />"; var expected = "See https://github.com"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See5() { var comment = @"See <see href=""https://github.com"">GitHub</see>"; var expected = "See GitHub"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See6() { var comment = @"See <see href=""https://github.com""></see>"; var expected = "See https://github.com"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso1() { var comment = @"See also <seealso cref=""T:System.Object"" />"; var expected = @"See also System.Object"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso2() { var comment = @"See also <seealso />"; var expected = @"See also"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso3() { var comment = @"See also <seealso langword=""true"" />"; var expected = "See also true"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso4() { var comment = @"See also <seealso href=""https://github.com"" />"; var expected = "See also https://github.com"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso5() { var comment = @"See also <seealso href=""https://github.com"">GitHub</seealso>"; var expected = "See also GitHub"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso6() { var comment = @"See also <seealso href=""https://github.com""></seealso>"; var expected = "See also https://github.com"; TestFormat(comment, expected); } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionGenerateSwitchCases.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions { internal sealed class SnippetFunctionGenerateSwitchCases : AbstractSnippetFunctionGenerateSwitchCases { public SnippetFunctionGenerateSwitchCases(SnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string caseGenerationLocationField, string switchExpressionField) : base(snippetExpansionClient, subjectBuffer, caseGenerationLocationField, switchExpressionField) { } protected override string CaseFormat { get { return @"case {0}.{1}: break; "; } } protected override string DefaultCase { get { return @"default: break;"; } } protected override bool TryGetEnumTypeSymbol(CancellationToken cancellationToken, [NotNullWhen(returnValue: true)] out ITypeSymbol? typeSymbol) { typeSymbol = null; if (!TryGetDocument(out var document)) { return false; } Contract.ThrowIfNull(_snippetExpansionClient.ExpansionSession); var subjectBufferFieldSpan = _snippetExpansionClient.ExpansionSession.GetFieldSpan(SwitchExpressionField); var expressionSpan = subjectBufferFieldSpan.Span.ToTextSpan(); var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var token = syntaxTree.FindTokenOnRightOfPosition(expressionSpan.Start, cancellationToken); var expressionNode = token.GetAncestor(n => n.Span == expressionSpan); if (expressionNode == null) { return false; } var model = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); typeSymbol = model?.GetTypeInfo(expressionNode, cancellationToken).Type; return typeSymbol != null; } protected override bool TryGetSimplifiedTypeNameInCaseContext(Document document, string fullyQualifiedTypeName, string firstEnumMemberName, int startPosition, int endPosition, CancellationToken cancellationToken, out string simplifiedTypeName) { simplifiedTypeName = string.Empty; var typeAnnotation = new SyntaxAnnotation(); var str = "case " + fullyQualifiedTypeName + "." + firstEnumMemberName + ":" + Environment.NewLine + " break;"; var textChange = new TextChange(new TextSpan(startPosition, endPosition - startPosition), str); var typeSpanToAnnotate = new TextSpan(startPosition + "case ".Length, fullyQualifiedTypeName.Length); var textWithCaseAdded = document.GetTextSynchronously(cancellationToken).WithChanges(textChange); var documentWithCaseAdded = document.WithText(textWithCaseAdded); var syntaxRoot = documentWithCaseAdded.GetRequiredSyntaxRootSynchronously(cancellationToken); var nodeToReplace = syntaxRoot.DescendantNodes().FirstOrDefault(n => n.Span == typeSpanToAnnotate); if (nodeToReplace == null) { return false; } var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation)); var documentWithAnnotations = documentWithCaseAdded.WithSyntaxRoot(updatedRoot); var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).Result; simplifiedTypeName = simplifiedDocument.GetRequiredSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString(); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions { internal sealed class SnippetFunctionGenerateSwitchCases : AbstractSnippetFunctionGenerateSwitchCases { public SnippetFunctionGenerateSwitchCases(SnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string caseGenerationLocationField, string switchExpressionField) : base(snippetExpansionClient, subjectBuffer, caseGenerationLocationField, switchExpressionField) { } protected override string CaseFormat { get { return @"case {0}.{1}: break; "; } } protected override string DefaultCase { get { return @"default: break;"; } } protected override bool TryGetEnumTypeSymbol(CancellationToken cancellationToken, [NotNullWhen(returnValue: true)] out ITypeSymbol? typeSymbol) { typeSymbol = null; if (!TryGetDocument(out var document)) { return false; } Contract.ThrowIfNull(_snippetExpansionClient.ExpansionSession); var subjectBufferFieldSpan = _snippetExpansionClient.ExpansionSession.GetFieldSpan(SwitchExpressionField); var expressionSpan = subjectBufferFieldSpan.Span.ToTextSpan(); var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var token = syntaxTree.FindTokenOnRightOfPosition(expressionSpan.Start, cancellationToken); var expressionNode = token.GetAncestor(n => n.Span == expressionSpan); if (expressionNode == null) { return false; } var model = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); typeSymbol = model?.GetTypeInfo(expressionNode, cancellationToken).Type; return typeSymbol != null; } protected override bool TryGetSimplifiedTypeNameInCaseContext(Document document, string fullyQualifiedTypeName, string firstEnumMemberName, int startPosition, int endPosition, CancellationToken cancellationToken, out string simplifiedTypeName) { simplifiedTypeName = string.Empty; var typeAnnotation = new SyntaxAnnotation(); var str = "case " + fullyQualifiedTypeName + "." + firstEnumMemberName + ":" + Environment.NewLine + " break;"; var textChange = new TextChange(new TextSpan(startPosition, endPosition - startPosition), str); var typeSpanToAnnotate = new TextSpan(startPosition + "case ".Length, fullyQualifiedTypeName.Length); var textWithCaseAdded = document.GetTextSynchronously(cancellationToken).WithChanges(textChange); var documentWithCaseAdded = document.WithText(textWithCaseAdded); var syntaxRoot = documentWithCaseAdded.GetRequiredSyntaxRootSynchronously(cancellationToken); var nodeToReplace = syntaxRoot.DescendantNodes().FirstOrDefault(n => n.Span == typeSpanToAnnotate); if (nodeToReplace == null) { return false; } var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation)); var documentWithAnnotations = documentWithCaseAdded.WithSyntaxRoot(updatedRoot); var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).Result; simplifiedTypeName = simplifiedDocument.GetRequiredSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString(); return true; } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Features/LanguageServer/Protocol/AbstractRequestDispatcherFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.LanguageServer.Handler; namespace Microsoft.CodeAnalysis.LanguageServer { /// <summary> /// Factory to handle creation of the <see cref="RequestDispatcher"/> /// </summary> internal abstract class AbstractRequestDispatcherFactory { protected readonly ImmutableArray<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> _requestHandlerProviders; protected AbstractRequestDispatcherFactory(IEnumerable<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> requestHandlerProviders) { _requestHandlerProviders = requestHandlerProviders.ToImmutableArray(); } /// <summary> /// Creates a new request dispatcher every time to ensure handlers are not shared /// and cleaned up appropriately on server restart. /// </summary> public virtual RequestDispatcher CreateRequestDispatcher(ImmutableArray<string> supportedLanguages) { return new RequestDispatcher(_requestHandlerProviders, supportedLanguages); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.LanguageServer.Handler; namespace Microsoft.CodeAnalysis.LanguageServer { /// <summary> /// Factory to handle creation of the <see cref="RequestDispatcher"/> /// </summary> internal abstract class AbstractRequestDispatcherFactory { protected readonly ImmutableArray<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> _requestHandlerProviders; protected AbstractRequestDispatcherFactory(IEnumerable<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> requestHandlerProviders) { _requestHandlerProviders = requestHandlerProviders.ToImmutableArray(); } /// <summary> /// Creates a new request dispatcher every time to ensure handlers are not shared /// and cleaned up appropriately on server restart. /// </summary> public virtual RequestDispatcher CreateRequestDispatcher(ImmutableArray<string> supportedLanguages) { return new RequestDispatcher(_requestHandlerProviders, supportedLanguages); } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/VisualStudio/Xaml/Impl/Diagnostics/Analyzers/IXamlDocumentAnalyzerService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Xaml.Diagnostics.Analyzers { internal interface IXamlDocumentAnalyzerService { ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Xaml.Diagnostics.Analyzers { internal interface IXamlDocumentAnalyzerService { ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Scripting/CoreTestUtilities/ObjectFormatterFixtures/Custom.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable 169 // unused field #pragma warning disable 649 // field not set, will always be default value using System; using System.Collections; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; namespace ObjectFormatterFixtures { internal class Outer { public class Nested<T> { public readonly int A = 1; public readonly int B = 2; public const int S = 3; } } internal class A<T> { public class B<S> { public class C { public class D<Q, R> { public class E { } } } } public static readonly B<T> X = new B<T>(); } internal class Sort { public readonly byte ab = 1; public readonly sbyte aB = -1; public readonly short Ac = -1; public readonly ushort Ad = 1; public readonly int ad = -1; public readonly uint aE = 1; public readonly long aF = -1; public readonly ulong AG = 1; } internal class Signatures { public static readonly MethodInfo Arrays = typeof(Signatures).GetMethod(nameof(ArrayParameters)); public void ArrayParameters(int[] arrayOne, int[,] arrayTwo, int[,,] arrayThree) { } } internal class RecursiveRootHidden { public readonly int A; public readonly int B; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public RecursiveRootHidden C; } internal class RecursiveProxy { private class Proxy { public Proxy() { } public Proxy(Node node) { x = node.value; y = node.next; } public readonly int x; public readonly Node y; } [DebuggerTypeProxy(typeof(Proxy))] public class Node { public Node(int value) { if (value < 5) { next = new Node(value + 1); } this.value = value; } public readonly int value; public readonly Node next; } } internal class InvalidRecursiveProxy { private class Proxy { public Proxy() { } public Proxy(Node c) { } public readonly int x; public readonly Node p = new Node(); public readonly int y; } [DebuggerTypeProxy(typeof(Proxy))] public class Node { public readonly int a; public readonly int b; } } internal class ComplexProxyBase { private int Goo() { return 1; } } internal class ComplexProxy : ComplexProxyBase { public ComplexProxy() { } public ComplexProxy(object b) { } [DebuggerDisplay("*1")] public int _02_public_property_dd { get { return 1; } } [DebuggerDisplay("*2")] private int _03_private_property_dd { get { return 1; } } [DebuggerDisplay("*3")] protected int _04_protected_property_dd { get { return 1; } } [DebuggerDisplay("*4")] internal int _05_internal_property_dd { get { return 1; } } [DebuggerDisplay("+1")] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public readonly int _06_public_field_dd_never; [DebuggerDisplay("+2")] private readonly int _07_private_field_dd; [DebuggerDisplay("+3")] protected readonly int _08_protected_field_dd; [DebuggerDisplay("+4")] internal readonly int _09_internal_field_dd; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] private readonly int _10_private_collapsed; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private readonly int _10_private_rootHidden; public readonly int _12_public; private readonly int _13_private; protected readonly int _14_protected; internal readonly int _15_internal; [DebuggerDisplay("==\r\n=\r\n=")] public readonly int _16_eolns; [DebuggerDisplay("=={==")] public readonly int _17_braces_0; [DebuggerDisplay("=={{==")] public readonly int _17_braces_1; [DebuggerDisplay("=={'{'}==")] public readonly int _17_braces_2; [DebuggerDisplay("=={'\\{'}==")] public readonly int _17_braces_3; [DebuggerDisplay("=={1/*{*/}==")] public readonly int _17_braces_4; [DebuggerDisplay("=={'{'/*\\}*/}==")] public readonly int _17_braces_5; [DebuggerDisplay("=={'{'/*}*/}==")] public readonly int _17_braces_6; [DebuggerDisplay("==\\{\\x\\t==")] public readonly int _19_escapes; [DebuggerDisplay("{1+1}")] public readonly int _21; [DebuggerDisplay("{\"xxx\"}")] public readonly int _22; [DebuggerDisplay("{\"xxx\",nq}")] public readonly int _23; [DebuggerDisplay("{'x'}")] public readonly int _24; [DebuggerDisplay("{'x',nq}")] public readonly int _25; [DebuggerDisplay("{new B()}")] public readonly int _26_0; [DebuggerDisplay("{new D()}")] public readonly int _26_1; [DebuggerDisplay("{new E()}")] public readonly int _26_2; [DebuggerDisplay("{ReturnVoid()}")] public readonly int _26_3; private void ReturnVoid() { } [DebuggerDisplay("{F1(1)}")] public readonly int _26_4; [DebuggerDisplay("{Goo}")] public readonly int _26_5; [DebuggerDisplay("{goo}")] public readonly int _26_6; private int goo() { return 2; } private int F1(int a) { return 1; } private int F2(short a) { return 2; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public readonly C _27_rootHidden = new C(); public readonly C _28 = new C(); [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public readonly C _29_collapsed = new C(); public int _31 { get; set; } [CompilerGenerated] public readonly int _32; [CompilerGenerated] private readonly int _33; public int _34_Exception { get { throw new Exception("error1"); } } [DebuggerDisplay("-!-")] public int _35_Exception { get { throw new Exception("error2"); } } public readonly object _36 = new ToStringException(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] public int _37 { get { throw new Exception("error3"); } } public int _38_private_get_public_set { private get { return 1; } set { } } public int _39_public_get_private_set { get { return 1; } private set { } } private int _40_private_get_private_set { get { return 1; } set { } } private int _41_set_only_property { set { } } public override string ToString() { return "AStr"; } } [DebuggerTypeProxy(typeof(ComplexProxy))] internal class TypeWithComplexProxy { public override string ToString() { return "BStr"; } } [DebuggerTypeProxy(typeof(Proxy))] [DebuggerDisplay("DD")] internal class TypeWithDebuggerDisplayAndProxy { public override string ToString() { return "<ToString>"; } [DebuggerDisplay("pxy")] private class Proxy { public Proxy(object x) { } public readonly int A; public readonly int B; } } internal class C { public readonly int A = 1; public readonly int B = 2; public override string ToString() { return "CStr"; } } [DebuggerDisplay("DebuggerDisplayValue")] internal class BaseClassWithDebuggerDisplay { } internal class InheritedDebuggerDisplay : BaseClassWithDebuggerDisplay { } internal class ToStringException { public override string ToString() { throw new MyException(); } } internal class MyException : Exception { public override string ToString() { return "my exception"; } } public class ThrowingDictionary : IDictionary { private readonly int _throwAt; public ThrowingDictionary(int throwAt) { _throwAt = throwAt; } public void Add(object key, object value) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(object key) { throw new NotImplementedException(); } public IDictionaryEnumerator GetEnumerator() { return new E(_throwAt); } public bool IsFixedSize { get { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public ICollection Keys { get { return new[] { 1, 2 }; } } public void Remove(object key) { } public ICollection Values { get { return new[] { 1, 2 }; } } public object this[object key] { get { return 1; } set { } } public void CopyTo(Array array, int index) { } public int Count { get { return 10; } } public bool IsSynchronized { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } IEnumerator IEnumerable.GetEnumerator() { return new E(-1); } private class E : IEnumerator, IDictionaryEnumerator { private int _i; private readonly int _throwAt; public E(int throwAt) { _throwAt = throwAt; } public object Current { get { return new DictionaryEntry(_i, _i); } } public bool MoveNext() { _i++; if (_i == _throwAt) { throw new Exception(); } return _i < 5; } public void Reset() { } public DictionaryEntry Entry { get { return (DictionaryEntry)Current; } } public object Key { get { return _i; } } public object Value { get { return _i; } } } } public class ListNode { public ListNode next; public object data; } public class LongMembers { public readonly string LongName0123456789_0123456789_0123456789_0123456789_0123456789_0123456789_0123456789 = "hello"; public readonly string LongValue = "0123456789_0123456789_0123456789_0123456789_0123456789_0123456789_0123456789"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable 169 // unused field #pragma warning disable 649 // field not set, will always be default value using System; using System.Collections; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; namespace ObjectFormatterFixtures { internal class Outer { public class Nested<T> { public readonly int A = 1; public readonly int B = 2; public const int S = 3; } } internal class A<T> { public class B<S> { public class C { public class D<Q, R> { public class E { } } } } public static readonly B<T> X = new B<T>(); } internal class Sort { public readonly byte ab = 1; public readonly sbyte aB = -1; public readonly short Ac = -1; public readonly ushort Ad = 1; public readonly int ad = -1; public readonly uint aE = 1; public readonly long aF = -1; public readonly ulong AG = 1; } internal class Signatures { public static readonly MethodInfo Arrays = typeof(Signatures).GetMethod(nameof(ArrayParameters)); public void ArrayParameters(int[] arrayOne, int[,] arrayTwo, int[,,] arrayThree) { } } internal class RecursiveRootHidden { public readonly int A; public readonly int B; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public RecursiveRootHidden C; } internal class RecursiveProxy { private class Proxy { public Proxy() { } public Proxy(Node node) { x = node.value; y = node.next; } public readonly int x; public readonly Node y; } [DebuggerTypeProxy(typeof(Proxy))] public class Node { public Node(int value) { if (value < 5) { next = new Node(value + 1); } this.value = value; } public readonly int value; public readonly Node next; } } internal class InvalidRecursiveProxy { private class Proxy { public Proxy() { } public Proxy(Node c) { } public readonly int x; public readonly Node p = new Node(); public readonly int y; } [DebuggerTypeProxy(typeof(Proxy))] public class Node { public readonly int a; public readonly int b; } } internal class ComplexProxyBase { private int Goo() { return 1; } } internal class ComplexProxy : ComplexProxyBase { public ComplexProxy() { } public ComplexProxy(object b) { } [DebuggerDisplay("*1")] public int _02_public_property_dd { get { return 1; } } [DebuggerDisplay("*2")] private int _03_private_property_dd { get { return 1; } } [DebuggerDisplay("*3")] protected int _04_protected_property_dd { get { return 1; } } [DebuggerDisplay("*4")] internal int _05_internal_property_dd { get { return 1; } } [DebuggerDisplay("+1")] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public readonly int _06_public_field_dd_never; [DebuggerDisplay("+2")] private readonly int _07_private_field_dd; [DebuggerDisplay("+3")] protected readonly int _08_protected_field_dd; [DebuggerDisplay("+4")] internal readonly int _09_internal_field_dd; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] private readonly int _10_private_collapsed; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private readonly int _10_private_rootHidden; public readonly int _12_public; private readonly int _13_private; protected readonly int _14_protected; internal readonly int _15_internal; [DebuggerDisplay("==\r\n=\r\n=")] public readonly int _16_eolns; [DebuggerDisplay("=={==")] public readonly int _17_braces_0; [DebuggerDisplay("=={{==")] public readonly int _17_braces_1; [DebuggerDisplay("=={'{'}==")] public readonly int _17_braces_2; [DebuggerDisplay("=={'\\{'}==")] public readonly int _17_braces_3; [DebuggerDisplay("=={1/*{*/}==")] public readonly int _17_braces_4; [DebuggerDisplay("=={'{'/*\\}*/}==")] public readonly int _17_braces_5; [DebuggerDisplay("=={'{'/*}*/}==")] public readonly int _17_braces_6; [DebuggerDisplay("==\\{\\x\\t==")] public readonly int _19_escapes; [DebuggerDisplay("{1+1}")] public readonly int _21; [DebuggerDisplay("{\"xxx\"}")] public readonly int _22; [DebuggerDisplay("{\"xxx\",nq}")] public readonly int _23; [DebuggerDisplay("{'x'}")] public readonly int _24; [DebuggerDisplay("{'x',nq}")] public readonly int _25; [DebuggerDisplay("{new B()}")] public readonly int _26_0; [DebuggerDisplay("{new D()}")] public readonly int _26_1; [DebuggerDisplay("{new E()}")] public readonly int _26_2; [DebuggerDisplay("{ReturnVoid()}")] public readonly int _26_3; private void ReturnVoid() { } [DebuggerDisplay("{F1(1)}")] public readonly int _26_4; [DebuggerDisplay("{Goo}")] public readonly int _26_5; [DebuggerDisplay("{goo}")] public readonly int _26_6; private int goo() { return 2; } private int F1(int a) { return 1; } private int F2(short a) { return 2; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public readonly C _27_rootHidden = new C(); public readonly C _28 = new C(); [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public readonly C _29_collapsed = new C(); public int _31 { get; set; } [CompilerGenerated] public readonly int _32; [CompilerGenerated] private readonly int _33; public int _34_Exception { get { throw new Exception("error1"); } } [DebuggerDisplay("-!-")] public int _35_Exception { get { throw new Exception("error2"); } } public readonly object _36 = new ToStringException(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] public int _37 { get { throw new Exception("error3"); } } public int _38_private_get_public_set { private get { return 1; } set { } } public int _39_public_get_private_set { get { return 1; } private set { } } private int _40_private_get_private_set { get { return 1; } set { } } private int _41_set_only_property { set { } } public override string ToString() { return "AStr"; } } [DebuggerTypeProxy(typeof(ComplexProxy))] internal class TypeWithComplexProxy { public override string ToString() { return "BStr"; } } [DebuggerTypeProxy(typeof(Proxy))] [DebuggerDisplay("DD")] internal class TypeWithDebuggerDisplayAndProxy { public override string ToString() { return "<ToString>"; } [DebuggerDisplay("pxy")] private class Proxy { public Proxy(object x) { } public readonly int A; public readonly int B; } } internal class C { public readonly int A = 1; public readonly int B = 2; public override string ToString() { return "CStr"; } } [DebuggerDisplay("DebuggerDisplayValue")] internal class BaseClassWithDebuggerDisplay { } internal class InheritedDebuggerDisplay : BaseClassWithDebuggerDisplay { } internal class ToStringException { public override string ToString() { throw new MyException(); } } internal class MyException : Exception { public override string ToString() { return "my exception"; } } public class ThrowingDictionary : IDictionary { private readonly int _throwAt; public ThrowingDictionary(int throwAt) { _throwAt = throwAt; } public void Add(object key, object value) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(object key) { throw new NotImplementedException(); } public IDictionaryEnumerator GetEnumerator() { return new E(_throwAt); } public bool IsFixedSize { get { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public ICollection Keys { get { return new[] { 1, 2 }; } } public void Remove(object key) { } public ICollection Values { get { return new[] { 1, 2 }; } } public object this[object key] { get { return 1; } set { } } public void CopyTo(Array array, int index) { } public int Count { get { return 10; } } public bool IsSynchronized { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } IEnumerator IEnumerable.GetEnumerator() { return new E(-1); } private class E : IEnumerator, IDictionaryEnumerator { private int _i; private readonly int _throwAt; public E(int throwAt) { _throwAt = throwAt; } public object Current { get { return new DictionaryEntry(_i, _i); } } public bool MoveNext() { _i++; if (_i == _throwAt) { throw new Exception(); } return _i < 5; } public void Reset() { } public DictionaryEntry Entry { get { return (DictionaryEntry)Current; } } public object Key { get { return _i; } } public object Value { get { return _i; } } } } public class ListNode { public ListNode next; public object data; } public class LongMembers { public readonly string LongName0123456789_0123456789_0123456789_0123456789_0123456789_0123456789_0123456789 = "hello"; public readonly string LongValue = "0123456789_0123456789_0123456789_0123456789_0123456789_0123456789_0123456789"; } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/EditorFeatures/Test/Extensions/CollectionExtensionsTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class CollectionExtensionsTest { [Fact] public void PushReverse1() { var stack = new Stack<int>(); stack.PushReverse(new int[] { 1, 2, 3 }); Assert.Equal(1, stack.Pop()); Assert.Equal(2, stack.Pop()); Assert.Equal(3, stack.Pop()); Assert.Equal(0, stack.Count); } [Fact] public void PushReverse2() { var stack = new Stack<int>(); stack.PushReverse(Array.Empty<int>()); Assert.Equal(0, stack.Count); } [Fact] public void PushReverse3() { var stack = new Stack<int>(); stack.Push(3); stack.PushReverse(new int[] { 1, 2 }); Assert.Equal(1, stack.Pop()); Assert.Equal(2, stack.Pop()); Assert.Equal(3, stack.Pop()); Assert.Equal(0, stack.Count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class CollectionExtensionsTest { [Fact] public void PushReverse1() { var stack = new Stack<int>(); stack.PushReverse(new int[] { 1, 2, 3 }); Assert.Equal(1, stack.Pop()); Assert.Equal(2, stack.Pop()); Assert.Equal(3, stack.Pop()); Assert.Equal(0, stack.Count); } [Fact] public void PushReverse2() { var stack = new Stack<int>(); stack.PushReverse(Array.Empty<int>()); Assert.Equal(0, stack.Count); } [Fact] public void PushReverse3() { var stack = new Stack<int>(); stack.Push(3); stack.PushReverse(new int[] { 1, 2 }); Assert.Equal(1, stack.Pop()); Assert.Equal(2, stack.Pop()); Assert.Equal(3, stack.Pop()); Assert.Equal(0, stack.Count); } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Tools/BuildValidator/Util.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; namespace BuildValidator { internal static class Util { internal static PortableExecutableInfo? GetPortableExecutableInfo(string filePath) { using var stream = File.OpenRead(filePath); var peReader = new PEReader(stream); if (GetMvid(peReader) is { } mvid) { var isReadyToRun = IsReadyToRunImage(peReader); return new PortableExecutableInfo(filePath, mvid, isReadyToRun); } return null; } internal static Guid? GetMvid(PEReader peReader) { if (peReader.HasMetadata) { var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } else { return null; } } internal static bool IsReadyToRunImage(PEReader peReader) { if (peReader.PEHeaders is null || peReader.PEHeaders.PEHeader is null || peReader.PEHeaders.CorHeader is null) { return false; } if ((peReader.PEHeaders.CorHeader.Flags & CorFlags.ILLibrary) == 0) { PEExportTable exportTable = peReader.GetExportTable(); return exportTable.TryGetValue("RTR_HEADER", out _); } else { return peReader.PEHeaders.CorHeader.ManagedNativeHeaderDirectory.Size != 0; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; namespace BuildValidator { internal static class Util { internal static PortableExecutableInfo? GetPortableExecutableInfo(string filePath) { using var stream = File.OpenRead(filePath); var peReader = new PEReader(stream); if (GetMvid(peReader) is { } mvid) { var isReadyToRun = IsReadyToRunImage(peReader); return new PortableExecutableInfo(filePath, mvid, isReadyToRun); } return null; } internal static Guid? GetMvid(PEReader peReader) { if (peReader.HasMetadata) { var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } else { return null; } } internal static bool IsReadyToRunImage(PEReader peReader) { if (peReader.PEHeaders is null || peReader.PEHeaders.PEHeader is null || peReader.PEHeaders.CorHeader is null) { return false; } if ((peReader.PEHeaders.CorHeader.Flags & CorFlags.ILLibrary) == 0) { PEExportTable exportTable = peReader.GetExportTable(); return exportTable.TryGetValue("RTR_HEADER", out _); } else { return peReader.PEHeaders.CorHeader.ManagedNativeHeaderDirectory.Size != 0; } } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxListExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class SyntaxListExtensions { public static SyntaxList<T> RemoveRange<T>(this SyntaxList<T> syntaxList, int index, int count) where T : SyntaxNode { var result = new List<T>(syntaxList); result.RemoveRange(index, count); return SyntaxFactory.List(result); } public static SyntaxList<T> ToSyntaxList<T>(this IEnumerable<T> sequence) where T : SyntaxNode => SyntaxFactory.List(sequence); public static SyntaxList<T> Insert<T>(this SyntaxList<T> list, int index, T item) where T : SyntaxNode => list.Take(index).Concat(item).Concat(list.Skip(index)).ToSyntaxList(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class SyntaxListExtensions { public static SyntaxList<T> RemoveRange<T>(this SyntaxList<T> syntaxList, int index, int count) where T : SyntaxNode { var result = new List<T>(syntaxList); result.RemoveRange(index, count); return SyntaxFactory.List(result); } public static SyntaxList<T> ToSyntaxList<T>(this IEnumerable<T> sequence) where T : SyntaxNode => SyntaxFactory.List(sequence); public static SyntaxList<T> Insert<T>(this SyntaxList<T> list, int index, T item) where T : SyntaxNode => list.Take(index).Concat(item).Concat(list.Skip(index)).ToSyntaxList(); } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/EditorFeatures/CSharpTest/Diagnostics/UpdateProjectToAllowUnsafe/UpdateProjectToAllowUnsafeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UpdateProjectToAllowUnsafe; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UpdateProjectToAllowUnsafe { [Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)] public class UpdateProjectToAllowUnsafeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UpdateProjectToAllowUnsafeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpUpdateProjectToAllowUnsafeCodeFixProvider()); private async Task TestAllowUnsafeEnabledIfDisabledAsync(string initialMarkup) { var parameters = new TestParameters(); using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var (_, action) = await GetCodeActionsAsync(workspace, parameters); var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default); var (oldSolution, newSolution) = ApplyOperationsAndGetSolution(workspace, operations); Assert.True(((CSharpCompilationOptions)newSolution.Projects.Single().CompilationOptions).AllowUnsafe); } // no action offered if unsafe was already enabled await TestMissingAsync(initialMarkup, new TestParameters(compilationOptions: new CSharpCompilationOptions(outputKind: default, allowUnsafe: true))); } [Fact] public async Task OnUnsafeClass() { await TestAllowUnsafeEnabledIfDisabledAsync( @" unsafe class [|C|] // The compiler reports this on the name, not the 'unsafe' keyword. { }"); } [Fact] public async Task OnUnsafeMethod() { await TestAllowUnsafeEnabledIfDisabledAsync( @" class C { unsafe void [|M|]() { } }"); } [Fact] public async Task OnUnsafeLocalFunction() { await TestAllowUnsafeEnabledIfDisabledAsync( @" class C { void M() { unsafe void [|F|]() { } } }"); } [Fact] public async Task OnUnsafeBlock() { await TestAllowUnsafeEnabledIfDisabledAsync( @" class C { void M() { [|unsafe|] { } } }"); } [Fact] public async Task NotInsideUnsafeBlock() { await TestMissingAsync( @" class C { void M() { unsafe { [|int * p;|] } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UpdateProjectToAllowUnsafe; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UpdateProjectToAllowUnsafe { [Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)] public class UpdateProjectToAllowUnsafeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UpdateProjectToAllowUnsafeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpUpdateProjectToAllowUnsafeCodeFixProvider()); private async Task TestAllowUnsafeEnabledIfDisabledAsync(string initialMarkup) { var parameters = new TestParameters(); using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var (_, action) = await GetCodeActionsAsync(workspace, parameters); var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default); var (oldSolution, newSolution) = ApplyOperationsAndGetSolution(workspace, operations); Assert.True(((CSharpCompilationOptions)newSolution.Projects.Single().CompilationOptions).AllowUnsafe); } // no action offered if unsafe was already enabled await TestMissingAsync(initialMarkup, new TestParameters(compilationOptions: new CSharpCompilationOptions(outputKind: default, allowUnsafe: true))); } [Fact] public async Task OnUnsafeClass() { await TestAllowUnsafeEnabledIfDisabledAsync( @" unsafe class [|C|] // The compiler reports this on the name, not the 'unsafe' keyword. { }"); } [Fact] public async Task OnUnsafeMethod() { await TestAllowUnsafeEnabledIfDisabledAsync( @" class C { unsafe void [|M|]() { } }"); } [Fact] public async Task OnUnsafeLocalFunction() { await TestAllowUnsafeEnabledIfDisabledAsync( @" class C { void M() { unsafe void [|F|]() { } } }"); } [Fact] public async Task OnUnsafeBlock() { await TestAllowUnsafeEnabledIfDisabledAsync( @" class C { void M() { [|unsafe|] { } } }"); } [Fact] public async Task NotInsideUnsafeBlock() { await TestMissingAsync( @" class C { void M() { unsafe { [|int * p;|] } } }"); } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Features/CSharp/Portable/ExtractMethod/CSharpSelectionResult.StatementResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpSelectionResult { private class StatementResult : CSharpSelectionResult { public StatementResult( OperationStatus status, TextSpan originalSpan, TextSpan finalSpan, OptionSet options, bool selectionInExpression, SemanticDocument document, SyntaxAnnotation firstTokenAnnotation, SyntaxAnnotation lastTokenAnnotation) : base(status, originalSpan, finalSpan, options, selectionInExpression, document, firstTokenAnnotation, lastTokenAnnotation) { } public override bool ContainingScopeHasAsyncKeyword() { var node = GetContainingScope(); return node switch { AccessorDeclarationSyntax _ => false, MethodDeclarationSyntax method => method.Modifiers.Any(SyntaxKind.AsyncKeyword), ParenthesizedLambdaExpressionSyntax lambda => lambda.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword, SimpleLambdaExpressionSyntax lambda => lambda.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword, AnonymousMethodExpressionSyntax anonymous => anonymous.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword, _ => false, }; } public override SyntaxNode GetContainingScope() { Contract.ThrowIfNull(SemanticDocument); Contract.ThrowIfTrue(SelectionInExpression); // it contains statements var firstToken = GetFirstTokenInSelection(); return firstToken.GetAncestors<SyntaxNode>().FirstOrDefault(n => { return n is AccessorDeclarationSyntax or LocalFunctionStatementSyntax or BaseMethodDeclarationSyntax or AccessorDeclarationSyntax or ParenthesizedLambdaExpressionSyntax or SimpleLambdaExpressionSyntax or AnonymousMethodExpressionSyntax or CompilationUnitSyntax; }); } public override ITypeSymbol GetContainingScopeType() { Contract.ThrowIfTrue(SelectionInExpression); var node = GetContainingScope(); var semanticModel = SemanticDocument.SemanticModel; switch (node) { case AccessorDeclarationSyntax access: // property or event case if (access.Parent == null || access.Parent.Parent == null) { return null; } return semanticModel.GetDeclaredSymbol(access.Parent.Parent) switch { IPropertySymbol propertySymbol => propertySymbol.Type, IEventSymbol eventSymbol => eventSymbol.Type, _ => null, }; case MethodDeclarationSyntax method: return semanticModel.GetDeclaredSymbol(method).ReturnType; case ParenthesizedLambdaExpressionSyntax lambda: return semanticModel.GetLambdaOrAnonymousMethodReturnType(lambda); case SimpleLambdaExpressionSyntax lambda: return semanticModel.GetLambdaOrAnonymousMethodReturnType(lambda); case AnonymousMethodExpressionSyntax anonymous: return semanticModel.GetLambdaOrAnonymousMethodReturnType(anonymous); default: return null; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpSelectionResult { private class StatementResult : CSharpSelectionResult { public StatementResult( OperationStatus status, TextSpan originalSpan, TextSpan finalSpan, OptionSet options, bool selectionInExpression, SemanticDocument document, SyntaxAnnotation firstTokenAnnotation, SyntaxAnnotation lastTokenAnnotation) : base(status, originalSpan, finalSpan, options, selectionInExpression, document, firstTokenAnnotation, lastTokenAnnotation) { } public override bool ContainingScopeHasAsyncKeyword() { var node = GetContainingScope(); return node switch { AccessorDeclarationSyntax _ => false, MethodDeclarationSyntax method => method.Modifiers.Any(SyntaxKind.AsyncKeyword), ParenthesizedLambdaExpressionSyntax lambda => lambda.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword, SimpleLambdaExpressionSyntax lambda => lambda.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword, AnonymousMethodExpressionSyntax anonymous => anonymous.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword, _ => false, }; } public override SyntaxNode GetContainingScope() { Contract.ThrowIfNull(SemanticDocument); Contract.ThrowIfTrue(SelectionInExpression); // it contains statements var firstToken = GetFirstTokenInSelection(); return firstToken.GetAncestors<SyntaxNode>().FirstOrDefault(n => { return n is AccessorDeclarationSyntax or LocalFunctionStatementSyntax or BaseMethodDeclarationSyntax or AccessorDeclarationSyntax or ParenthesizedLambdaExpressionSyntax or SimpleLambdaExpressionSyntax or AnonymousMethodExpressionSyntax or CompilationUnitSyntax; }); } public override ITypeSymbol GetContainingScopeType() { Contract.ThrowIfTrue(SelectionInExpression); var node = GetContainingScope(); var semanticModel = SemanticDocument.SemanticModel; switch (node) { case AccessorDeclarationSyntax access: // property or event case if (access.Parent == null || access.Parent.Parent == null) { return null; } return semanticModel.GetDeclaredSymbol(access.Parent.Parent) switch { IPropertySymbol propertySymbol => propertySymbol.Type, IEventSymbol eventSymbol => eventSymbol.Type, _ => null, }; case MethodDeclarationSyntax method: return semanticModel.GetDeclaredSymbol(method).ReturnType; case ParenthesizedLambdaExpressionSyntax lambda: return semanticModel.GetLambdaOrAnonymousMethodReturnType(lambda); case SimpleLambdaExpressionSyntax lambda: return semanticModel.GetLambdaOrAnonymousMethodReturnType(lambda); case AnonymousMethodExpressionSyntax anonymous: return semanticModel.GetLambdaOrAnonymousMethodReturnType(anonymous); default: return null; } } } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Features/LanguageServer/ProtocolUnitTests/Symbols/DocumentSymbolsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Symbols { public class DocumentSymbolsTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGetDocumentSymbolsAsync() { var markup = @"{|class:class {|classSelection:A|} { {|method:void {|methodSelection:M|}() { }|} }|}"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expected = new LSP.DocumentSymbol[] { CreateDocumentSymbol(LSP.SymbolKind.Class, "A", "A", locations["class"].Single(), locations["classSelection"].Single()) }; CreateDocumentSymbol(LSP.SymbolKind.Method, "M", "M()", locations["method"].Single(), locations["methodSelection"].Single(), expected.First()); var results = await RunGetDocumentSymbolsAsync(testLspServer, true); AssertJsonEquals(expected, results); } [Fact] public async Task TestGetDocumentSymbolsAsync__WithoutHierarchicalSupport() { var markup = @"class {|class:A|} { void {|method:M|}() { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expected = new LSP.SymbolInformation[] { CreateSymbolInformation(LSP.SymbolKind.Class, "A", locations["class"].Single(), Glyph.ClassInternal), CreateSymbolInformation(LSP.SymbolKind.Method, "M()", locations["method"].Single(), Glyph.MethodPrivate, "A") }; var results = await RunGetDocumentSymbolsAsync(testLspServer, false); AssertJsonEquals(expected, results); } [Fact(Skip = "GetDocumentSymbolsAsync does not yet support locals.")] // TODO - Remove skip & modify once GetDocumentSymbolsAsync is updated to support more than 2 levels. // https://github.com/dotnet/roslyn/projects/45#card-20033869 public async Task TestGetDocumentSymbolsAsync__WithLocals() { var markup = @"class A { void Method() { int i = 1; } }"; using var testLspServer = CreateTestLspServer(markup, out var _); var results = await RunGetDocumentSymbolsAsync(testLspServer, false).ConfigureAwait(false); Assert.Equal(3, results.Length); } [Fact] public async Task TestGetDocumentSymbolsAsync__NoSymbols() { using var testLspServer = CreateTestLspServer(string.Empty, out var _); var results = await RunGetDocumentSymbolsAsync(testLspServer, true); Assert.Empty(results); } private static async Task<object[]> RunGetDocumentSymbolsAsync(TestLspServer testLspServer, bool hierarchicalSupport) { var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var request = new LSP.DocumentSymbolParams { TextDocument = CreateTextDocumentIdentifier(new Uri(document.FilePath)) }; var clientCapabilities = new LSP.ClientCapabilities() { TextDocument = new LSP.TextDocumentClientCapabilities() { DocumentSymbol = new LSP.DocumentSymbolSetting() { HierarchicalDocumentSymbolSupport = hierarchicalSupport } } }; return await testLspServer.ExecuteRequestAsync<LSP.DocumentSymbolParams, object[]>(LSP.Methods.TextDocumentDocumentSymbolName, request, clientCapabilities, null, CancellationToken.None); } private static void AssertDocumentSymbolEquals(LSP.DocumentSymbol expected, LSP.DocumentSymbol actual) { Assert.Equal(expected.Kind, actual.Kind); Assert.Equal(expected.Name, actual.Name); Assert.Equal(expected.Range, actual.Range); Assert.Equal(expected.Children.Length, actual.Children.Length); for (var i = 0; i < actual.Children.Length; i++) { AssertDocumentSymbolEquals(expected.Children[i], actual.Children[i]); } } private static LSP.DocumentSymbol CreateDocumentSymbol(LSP.SymbolKind kind, string name, string detail, LSP.Location location, LSP.Location selection, LSP.DocumentSymbol parent = null) { var documentSymbol = new LSP.DocumentSymbol() { Kind = kind, Name = name, Range = location.Range, Children = new LSP.DocumentSymbol[0], Detail = detail, Deprecated = false, SelectionRange = selection.Range }; if (parent != null) { var children = parent.Children.ToList(); children.Add(documentSymbol); parent.Children = children.ToArray(); } return documentSymbol; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Symbols { public class DocumentSymbolsTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGetDocumentSymbolsAsync() { var markup = @"{|class:class {|classSelection:A|} { {|method:void {|methodSelection:M|}() { }|} }|}"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expected = new LSP.DocumentSymbol[] { CreateDocumentSymbol(LSP.SymbolKind.Class, "A", "A", locations["class"].Single(), locations["classSelection"].Single()) }; CreateDocumentSymbol(LSP.SymbolKind.Method, "M", "M()", locations["method"].Single(), locations["methodSelection"].Single(), expected.First()); var results = await RunGetDocumentSymbolsAsync(testLspServer, true); AssertJsonEquals(expected, results); } [Fact] public async Task TestGetDocumentSymbolsAsync__WithoutHierarchicalSupport() { var markup = @"class {|class:A|} { void {|method:M|}() { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expected = new LSP.SymbolInformation[] { CreateSymbolInformation(LSP.SymbolKind.Class, "A", locations["class"].Single(), Glyph.ClassInternal), CreateSymbolInformation(LSP.SymbolKind.Method, "M()", locations["method"].Single(), Glyph.MethodPrivate, "A") }; var results = await RunGetDocumentSymbolsAsync(testLspServer, false); AssertJsonEquals(expected, results); } [Fact(Skip = "GetDocumentSymbolsAsync does not yet support locals.")] // TODO - Remove skip & modify once GetDocumentSymbolsAsync is updated to support more than 2 levels. // https://github.com/dotnet/roslyn/projects/45#card-20033869 public async Task TestGetDocumentSymbolsAsync__WithLocals() { var markup = @"class A { void Method() { int i = 1; } }"; using var testLspServer = CreateTestLspServer(markup, out var _); var results = await RunGetDocumentSymbolsAsync(testLspServer, false).ConfigureAwait(false); Assert.Equal(3, results.Length); } [Fact] public async Task TestGetDocumentSymbolsAsync__NoSymbols() { using var testLspServer = CreateTestLspServer(string.Empty, out var _); var results = await RunGetDocumentSymbolsAsync(testLspServer, true); Assert.Empty(results); } private static async Task<object[]> RunGetDocumentSymbolsAsync(TestLspServer testLspServer, bool hierarchicalSupport) { var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var request = new LSP.DocumentSymbolParams { TextDocument = CreateTextDocumentIdentifier(new Uri(document.FilePath)) }; var clientCapabilities = new LSP.ClientCapabilities() { TextDocument = new LSP.TextDocumentClientCapabilities() { DocumentSymbol = new LSP.DocumentSymbolSetting() { HierarchicalDocumentSymbolSupport = hierarchicalSupport } } }; return await testLspServer.ExecuteRequestAsync<LSP.DocumentSymbolParams, object[]>(LSP.Methods.TextDocumentDocumentSymbolName, request, clientCapabilities, null, CancellationToken.None); } private static void AssertDocumentSymbolEquals(LSP.DocumentSymbol expected, LSP.DocumentSymbol actual) { Assert.Equal(expected.Kind, actual.Kind); Assert.Equal(expected.Name, actual.Name); Assert.Equal(expected.Range, actual.Range); Assert.Equal(expected.Children.Length, actual.Children.Length); for (var i = 0; i < actual.Children.Length; i++) { AssertDocumentSymbolEquals(expected.Children[i], actual.Children[i]); } } private static LSP.DocumentSymbol CreateDocumentSymbol(LSP.SymbolKind kind, string name, string detail, LSP.Location location, LSP.Location selection, LSP.DocumentSymbol parent = null) { var documentSymbol = new LSP.DocumentSymbol() { Kind = kind, Name = name, Range = location.Range, Children = new LSP.DocumentSymbol[0], Detail = detail, Deprecated = false, SelectionRange = selection.Range }; if (parent != null) { var children = parent.Children.ToList(); children.Add(documentSymbol); parent.Children = children.ToArray(); } return documentSymbol; } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpParenthesizedExpressionReducer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpParenthesizedExpressionReducer : AbstractCSharpReducer { private static readonly ObjectPool<IReductionRewriter> s_pool = new( () => new Rewriter(s_pool)); public CSharpParenthesizedExpressionReducer() : base(s_pool) { } private static readonly Func<ParenthesizedExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyParentheses = SimplifyParentheses; private static SyntaxNode SimplifyParentheses( ParenthesizedExpressionSyntax node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { if (node.CanRemoveParentheses(semanticModel, cancellationToken)) { // TODO(DustinCa): We should not be skipping elastic trivia below. // However, the formatter seems to mess up trailing trivia in some // cases if elastic trivia is there -- and it's not clear why. // Specifically remove the elastic trivia formatting rule doesn't // have any effect. var resultNode = CSharpSyntaxFacts.Instance.Unparenthesize(node); return SimplificationHelpers.CopyAnnotations(from: node, to: resultNode); } // We don't know how to simplify this. return node; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpParenthesizedExpressionReducer : AbstractCSharpReducer { private static readonly ObjectPool<IReductionRewriter> s_pool = new( () => new Rewriter(s_pool)); public CSharpParenthesizedExpressionReducer() : base(s_pool) { } private static readonly Func<ParenthesizedExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyParentheses = SimplifyParentheses; private static SyntaxNode SimplifyParentheses( ParenthesizedExpressionSyntax node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { if (node.CanRemoveParentheses(semanticModel, cancellationToken)) { // TODO(DustinCa): We should not be skipping elastic trivia below. // However, the formatter seems to mess up trailing trivia in some // cases if elastic trivia is there -- and it's not clear why. // Specifically remove the elastic trivia formatting rule doesn't // have any effect. var resultNode = CSharpSyntaxFacts.Instance.Unparenthesize(node); return SimplificationHelpers.CopyAnnotations(from: node, to: resultNode); } // We don't know how to simplify this. return node; } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Features/Core/Portable/GenerateOverrides/GenerateOverridesOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.GenerateOverrides { internal class GenerateOverridesOptions { public static readonly Option2<bool> SelectAll = new( nameof(GenerateOverridesOptions), nameof(SelectAll), defaultValue: true, storageLocation: new RoamingProfileStorageLocation($"TextEditor.Specific.{nameof(GenerateOverridesOptions)}.{nameof(SelectAll)}")); [ExportOptionProvider, Shared] internal class GenerateOverridesOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GenerateOverridesOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( GenerateOverridesOptions.SelectAll); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.GenerateOverrides { internal class GenerateOverridesOptions { public static readonly Option2<bool> SelectAll = new( nameof(GenerateOverridesOptions), nameof(SelectAll), defaultValue: true, storageLocation: new RoamingProfileStorageLocation($"TextEditor.Specific.{nameof(GenerateOverridesOptions)}.{nameof(SelectAll)}")); [ExportOptionProvider, Shared] internal class GenerateOverridesOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GenerateOverridesOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( GenerateOverridesOptions.SelectAll); } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Compilers/CSharp/Portable/Errors/LazyObsoleteDiagnosticInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LazyObsoleteDiagnosticInfo : DiagnosticInfo { private DiagnosticInfo _lazyActualObsoleteDiagnostic; private readonly object _symbolOrSymbolWithAnnotations; private readonly Symbol _containingSymbol; private readonly BinderFlags _binderFlags; internal LazyObsoleteDiagnosticInfo(object symbol, Symbol containingSymbol, BinderFlags binderFlags) : base(CSharp.MessageProvider.Instance, (int)ErrorCode.Unknown) { Debug.Assert(symbol is Symbol || symbol is TypeWithAnnotations); _symbolOrSymbolWithAnnotations = symbol; _containingSymbol = containingSymbol; _binderFlags = binderFlags; _lazyActualObsoleteDiagnostic = null; } internal override DiagnosticInfo GetResolvedInfo() { if (_lazyActualObsoleteDiagnostic == null) { // A symbol's Obsoleteness may not have been calculated yet if the symbol is coming // from a different compilation's source. In that case, force completion of attributes. var symbol = (_symbolOrSymbolWithAnnotations as Symbol) ?? ((TypeWithAnnotations)_symbolOrSymbolWithAnnotations).Type; symbol.ForceCompleteObsoleteAttribute(); var kind = ObsoleteAttributeHelpers.GetObsoleteDiagnosticKind(symbol, _containingSymbol, forceComplete: true); Debug.Assert(kind != ObsoleteDiagnosticKind.Lazy); Debug.Assert(kind != ObsoleteDiagnosticKind.LazyPotentiallySuppressed); var info = (kind == ObsoleteDiagnosticKind.Diagnostic) ? ObsoleteAttributeHelpers.CreateObsoleteDiagnostic(symbol, _binderFlags) : null; // If this symbol is not obsolete or is in an obsolete context, we don't want to report any diagnostics. // Therefore make this a Void diagnostic. Interlocked.CompareExchange(ref _lazyActualObsoleteDiagnostic, info ?? CSDiagnosticInfo.VoidDiagnosticInfo, null); } return _lazyActualObsoleteDiagnostic; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LazyObsoleteDiagnosticInfo : DiagnosticInfo { private DiagnosticInfo _lazyActualObsoleteDiagnostic; private readonly object _symbolOrSymbolWithAnnotations; private readonly Symbol _containingSymbol; private readonly BinderFlags _binderFlags; internal LazyObsoleteDiagnosticInfo(object symbol, Symbol containingSymbol, BinderFlags binderFlags) : base(CSharp.MessageProvider.Instance, (int)ErrorCode.Unknown) { Debug.Assert(symbol is Symbol || symbol is TypeWithAnnotations); _symbolOrSymbolWithAnnotations = symbol; _containingSymbol = containingSymbol; _binderFlags = binderFlags; _lazyActualObsoleteDiagnostic = null; } internal override DiagnosticInfo GetResolvedInfo() { if (_lazyActualObsoleteDiagnostic == null) { // A symbol's Obsoleteness may not have been calculated yet if the symbol is coming // from a different compilation's source. In that case, force completion of attributes. var symbol = (_symbolOrSymbolWithAnnotations as Symbol) ?? ((TypeWithAnnotations)_symbolOrSymbolWithAnnotations).Type; symbol.ForceCompleteObsoleteAttribute(); var kind = ObsoleteAttributeHelpers.GetObsoleteDiagnosticKind(symbol, _containingSymbol, forceComplete: true); Debug.Assert(kind != ObsoleteDiagnosticKind.Lazy); Debug.Assert(kind != ObsoleteDiagnosticKind.LazyPotentiallySuppressed); var info = (kind == ObsoleteDiagnosticKind.Diagnostic) ? ObsoleteAttributeHelpers.CreateObsoleteDiagnostic(symbol, _binderFlags) : null; // If this symbol is not obsolete or is in an obsolete context, we don't want to report any diagnostics. // Therefore make this a Void diagnostic. Interlocked.CompareExchange(ref _lazyActualObsoleteDiagnostic, info ?? CSDiagnosticInfo.VoidDiagnosticInfo, null); } return _lazyActualObsoleteDiagnostic; } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Workspaces/Remote/ServiceHub/Host/Storage/RemoteCloudCacheStorageServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote.Host; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Storage.CloudCache; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Storage; using Microsoft.VisualStudio.RpcContracts.Caching; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote.Storage { [ExportWorkspaceService(typeof(ICloudCacheStorageServiceFactory), WorkspaceKind.RemoteWorkspace), Shared] internal class RemoteCloudCacheStorageServiceFactory : ICloudCacheStorageServiceFactory { private readonly IGlobalServiceBroker _globalServiceBroker; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteCloudCacheStorageServiceFactory(IGlobalServiceBroker globalServiceBroker) { _globalServiceBroker = globalServiceBroker; } public AbstractPersistentStorageService Create(IPersistentStorageConfiguration configuration) => new RemoteCloudCachePersistentStorageService(_globalServiceBroker, configuration); private class RemoteCloudCachePersistentStorageService : AbstractCloudCachePersistentStorageService { private readonly IGlobalServiceBroker _globalServiceBroker; public RemoteCloudCachePersistentStorageService(IGlobalServiceBroker globalServiceBroker, IPersistentStorageConfiguration configuration) : base(configuration) { _globalServiceBroker = globalServiceBroker; } protected override void DisposeCacheService(ICacheService cacheService) { if (cacheService is IAsyncDisposable asyncDisposable) { asyncDisposable.DisposeAsync().AsTask().Wait(); } else if (cacheService is IDisposable disposable) { disposable.Dispose(); } } protected override async ValueTask<ICacheService> CreateCacheServiceAsync(CancellationToken cancellationToken) { var serviceBroker = _globalServiceBroker.Instance; #pragma warning disable ISB001 // Dispose of proxies // cache service will be disposed inside RemoteCloudCacheService.Dispose var cacheService = await serviceBroker.GetProxyAsync<ICacheService>(VisualStudioServices.VS2019_10.CacheService, cancellationToken: cancellationToken).ConfigureAwait(false); #pragma warning restore ISB001 // Dispose of proxies Contract.ThrowIfNull(cacheService); return cacheService; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote.Host; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Storage.CloudCache; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Storage; using Microsoft.VisualStudio.RpcContracts.Caching; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote.Storage { [ExportWorkspaceService(typeof(ICloudCacheStorageServiceFactory), WorkspaceKind.RemoteWorkspace), Shared] internal class RemoteCloudCacheStorageServiceFactory : ICloudCacheStorageServiceFactory { private readonly IGlobalServiceBroker _globalServiceBroker; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteCloudCacheStorageServiceFactory(IGlobalServiceBroker globalServiceBroker) { _globalServiceBroker = globalServiceBroker; } public AbstractPersistentStorageService Create(IPersistentStorageConfiguration configuration) => new RemoteCloudCachePersistentStorageService(_globalServiceBroker, configuration); private class RemoteCloudCachePersistentStorageService : AbstractCloudCachePersistentStorageService { private readonly IGlobalServiceBroker _globalServiceBroker; public RemoteCloudCachePersistentStorageService(IGlobalServiceBroker globalServiceBroker, IPersistentStorageConfiguration configuration) : base(configuration) { _globalServiceBroker = globalServiceBroker; } protected override void DisposeCacheService(ICacheService cacheService) { if (cacheService is IAsyncDisposable asyncDisposable) { asyncDisposable.DisposeAsync().AsTask().Wait(); } else if (cacheService is IDisposable disposable) { disposable.Dispose(); } } protected override async ValueTask<ICacheService> CreateCacheServiceAsync(CancellationToken cancellationToken) { var serviceBroker = _globalServiceBroker.Instance; #pragma warning disable ISB001 // Dispose of proxies // cache service will be disposed inside RemoteCloudCacheService.Dispose var cacheService = await serviceBroker.GetProxyAsync<ICacheService>(VisualStudioServices.VS2019_10.CacheService, cancellationToken: cancellationToken).ConfigureAwait(false); #pragma warning restore ISB001 // Dispose of proxies Contract.ThrowIfNull(cacheService); return cacheService; } } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Workspaces/CoreTest/SolutionTests/ProjectDependencyGraphTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Host.UnitTests { [UseExportProvider] public class ProjectDependencyGraphTests : TestBase { #region GetTopologicallySortedProjects [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestGetTopologicallySortedProjects() { VerifyTopologicalSort(CreateSolutionFromReferenceMap("A"), "A"); VerifyTopologicalSort(CreateSolutionFromReferenceMap("A B"), "AB", "BA"); VerifyTopologicalSort(CreateSolutionFromReferenceMap("C:A,B B:A A"), "ABC"); VerifyTopologicalSort(CreateSolutionFromReferenceMap("B:A A C:A D:C,B"), "ABCD", "ACBD"); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTopologicallySortedProjectsIncrementalUpdate() { var solution = CreateSolutionFromReferenceMap("A"); VerifyTopologicalSort(solution, "A"); solution = AddProject(solution, "B"); VerifyTopologicalSort(solution, "AB", "BA"); } /// <summary> /// Verifies that <see cref="ProjectDependencyGraph.GetTopologicallySortedProjects(CancellationToken)"/> /// returns one of the correct results. /// </summary> /// <param name="solution"></param> /// <param name="expectedResults">A list of possible results. Because topological sorting is ambiguous /// in that a graph could have multiple topological sorts, this helper lets you give all the possible /// results and it asserts that one of them does match.</param> private static void VerifyTopologicalSort(Solution solution, params string[] expectedResults) { var projectDependencyGraph = solution.GetProjectDependencyGraph(); var projectIds = projectDependencyGraph.GetTopologicallySortedProjects(CancellationToken.None); var actualResult = string.Concat(projectIds.Select(id => solution.GetRequiredProject(id).AssemblyName)); Assert.Contains<string>(actualResult, expectedResults); } #endregion #region Dependency Sets [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] [WorkItem(542438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542438")] public void TestGetDependencySets() { VerifyDependencySets(CreateSolutionFromReferenceMap("A B:A C:A D E:D F:D"), "ABC DEF"); VerifyDependencySets(CreateSolutionFromReferenceMap("A B:A,C C"), "ABC"); VerifyDependencySets(CreateSolutionFromReferenceMap("A B"), "A B"); VerifyDependencySets(CreateSolutionFromReferenceMap("A B C:B"), "A BC"); VerifyDependencySets(CreateSolutionFromReferenceMap("A B:A C:A D:B,C"), "ABCD"); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestDependencySetsIncrementalUpdate() { var solution = CreateSolutionFromReferenceMap("A"); VerifyDependencySets(solution, "A"); solution = AddProject(solution, "B"); VerifyDependencySets(solution, "A B"); } private static void VerifyDependencySets(Solution solution, string expectedResult) { var projectDependencyGraph = solution.GetProjectDependencyGraph(); var projectIds = projectDependencyGraph.GetDependencySets(CancellationToken.None); var actualResult = string.Join(" ", projectIds.Select( group => string.Concat( group.Select(p => solution.GetRequiredProject(p).AssemblyName).OrderBy(n => n))).OrderBy(n => n)); Assert.Equal(expectedResult, actualResult); } #endregion #region GetProjectsThatThisProjectTransitivelyDependsOn [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestGetProjectsThatThisProjectTransitivelyDependsOn() { VerifyTransitiveReferences(CreateSolutionFromReferenceMap("A"), "A", new string[] { }); VerifyTransitiveReferences(CreateSolutionFromReferenceMap("B:A A"), "B", new string[] { "A" }); VerifyTransitiveReferences(CreateSolutionFromReferenceMap("C:B B:A A"), "C", new string[] { "B", "A" }); VerifyTransitiveReferences(CreateSolutionFromReferenceMap("C:B B:A A"), "A", new string[] { }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestGetProjectsThatThisProjectTransitivelyDependsOnThrowsArgumentNull() { var solution = CreateSolutionFromReferenceMap(""); Assert.Throws<ArgumentNullException>("projectId", () => solution.GetProjectDependencyGraph().GetProjectsThatThisProjectDirectlyDependsOn(null!)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTransitiveReferencesIncrementalUpdateInMiddle() { // We are going to create a solution with the references: // // A -> B -> C -> D // // but we will add the B -> C link last, to verify that when we add the B to C link we update the references of A. var solution = CreateSolutionFromReferenceMap("A B C D"); VerifyTransitiveReferences(solution, "A", new string[] { }); VerifyTransitiveReferences(solution, "B", new string[] { }); VerifyTransitiveReferences(solution, "C", new string[] { }); VerifyTransitiveReferences(solution, "D", new string[] { }); solution = AddProjectReferences(solution, "A", new string[] { "B" }); solution = AddProjectReferences(solution, "C", new string[] { "D" }); VerifyDirectReferences(solution, "A", new string[] { "B" }); VerifyDirectReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "A", new string[] { "B" }); VerifyTransitiveReferences(solution, "B", new string[] { }); VerifyTransitiveReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "D", new string[] { }); solution = AddProjectReferences(solution, "B", new string[] { "C" }); VerifyDirectReferences(solution, "B", new string[] { "C" }); VerifyTransitiveReferences(solution, "A", new string[] { "B", "C", "D" }); VerifyTransitiveReferences(solution, "B", new string[] { "C", "D" }); VerifyTransitiveReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "D", new string[] { }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTransitiveReferencesIncrementalUpdateInMiddleLongerChain() { // We are going to create a solution with the references: // // A -> B -> C D -> E -> F // // but we will add the C-> D link last, to verify that when we add the C to D link we update the references of A. This is similar // to the previous test but with a longer chain. var solution = CreateSolutionFromReferenceMap("A:B B:C C D:E E:F F"); VerifyTransitiveReferences(solution, "A", new string[] { "B", "C" }); VerifyTransitiveReferences(solution, "B", new string[] { "C" }); VerifyTransitiveReferences(solution, "D", new string[] { "E", "F" }); VerifyTransitiveReferences(solution, "E", new string[] { "F" }); solution = AddProjectReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "A", new string[] { "B", "C", "D", "E", "F" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTransitiveReferencesIncrementalUpdateWithReferencesAlreadyTransitivelyIncluded() { // We are going to create a solution with the references: // // A -> B -> C // // and then we'll add a reference from A -> C, and transitive references should be different var solution = CreateSolutionFromReferenceMap("A:B B:C C"); void VerifyAllTransitiveReferences() { VerifyTransitiveReferences(solution, "A", new string[] { "B", "C" }); VerifyTransitiveReferences(solution, "B", new string[] { "C" }); VerifyTransitiveReferences(solution, "C", new string[] { }); } VerifyAllTransitiveReferences(); VerifyDirectReferences(solution, "A", new string[] { "B" }); solution = AddProjectReferences(solution, "A", new string[] { "C" }); VerifyAllTransitiveReferences(); VerifyDirectReferences(solution, "A", new string[] { "B", "C" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTransitiveReferencesIncrementalUpdateWithProjectThatHasUnknownReferences() { // We are going to create a solution with the references: // // A B C -> D // // and then we will add a link from A to B. We won't ask for transitive references first, // so we shouldn't have any information for A, B, or C and have to deal with that. var solution = CreateSolutionFromReferenceMap("A B C:D D"); solution = solution.WithProjectReferences(solution.GetProjectsByName("C").Single().Id, SpecializedCollections.EmptyEnumerable<ProjectReference>()); VerifyTransitiveReferences(solution, "A", new string[] { }); // At this point, we know the references for "A" (it's empty), but B and C's are still unknown. // At this point, we're also going to directly use the underlying project graph APIs; // the higher level solution APIs often call and ask for transitive information as well, which makes // this particularly hard to test -- it turns out the data we think is uncomputed might be computed prior // to adding the reference. var dependencyGraph = solution.GetProjectDependencyGraph(); var projectAId = solution.GetProjectsByName("A").Single().Id; var projectBId = solution.GetProjectsByName("B").Single().Id; dependencyGraph = dependencyGraph.WithAdditionalProjectReferences(projectAId, new[] { new ProjectReference(projectBId) }); VerifyTransitiveReferences(solution, dependencyGraph, project: "A", expectedResults: new string[] { "B" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTransitiveReferencesWithDanglingProjectReference() { // We are going to create a solution with the references: // // A -> B // // but we're going to add A as a reference with B not existing yet. Then we'll add in B and ask. var solution = CreateSolution(); var projectAId = ProjectId.CreateNewId("A"); var projectBId = ProjectId.CreateNewId("B"); var projectAInfo = ProjectInfo.Create(projectAId, VersionStamp.Create(), "A", "A", LanguageNames.CSharp, projectReferences: new[] { new ProjectReference(projectBId) }); solution = solution.AddProject(projectAInfo); VerifyDirectReferences(solution, "A", new string[] { }); VerifyTransitiveReferences(solution, "A", new string[] { }); solution = solution.AddProject(projectBId, "B", "B", LanguageNames.CSharp); VerifyTransitiveReferences(solution, "A", new string[] { "B" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTransitiveReferencesWithMultipleReferences() { // We are going to create a solution with the references: // // A B -> C D -> E // // and then add A referencing B and D in one call, to make sure that works. var solution = CreateSolutionFromReferenceMap("A B:C C D:E E"); VerifyTransitiveReferences(solution, "A", new string[] { }); solution = AddProjectReferences(solution, "A", new string[] { "B", "D" }); VerifyDirectReferences(solution, "A", new string[] { "B", "D" }); VerifyTransitiveReferences(solution, "A", new string[] { "B", "C", "D", "E" }); } private static void VerifyDirectReferences(Solution solution, string project, string[] expectedResults) { var projectDependencyGraph = solution.GetProjectDependencyGraph(); var projectId = solution.GetProjectsByName(project).Single().Id; var projectIds = projectDependencyGraph.GetProjectsThatThisProjectDirectlyDependsOn(projectId); var actualResults = projectIds.Select(id => solution.GetRequiredProject(id).Name); Assert.Equal<string>( expectedResults.OrderBy(n => n), actualResults.OrderBy(n => n)); } private static void VerifyTransitiveReferences(Solution solution, string project, string[] expectedResults) { var projectDependencyGraph = solution.GetProjectDependencyGraph(); VerifyTransitiveReferences(solution, projectDependencyGraph, project, expectedResults); } private static void VerifyTransitiveReferences(Solution solution, ProjectDependencyGraph projectDependencyGraph, string project, string[] expectedResults) { var projectId = solution.GetProjectsByName(project).Single().Id; var projectIds = projectDependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(projectId); var actualResults = projectIds.Select(id => solution.GetRequiredProject(id).Name); Assert.Equal<string>( expectedResults.OrderBy(n => n), actualResults.OrderBy(n => n)); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestDirectAndReverseDirectReferencesAfterWithProjectReferences() { var solution = CreateSolutionFromReferenceMap("A:B B"); VerifyDirectReverseReferences(solution, "B", new string[] { "A" }); solution = solution.WithProjectReferences(solution.GetProjectsByName("A").Single().Id, Enumerable.Empty<ProjectReference>()); VerifyDirectReferences(solution, "A", new string[] { }); VerifyDirectReverseReferences(solution, "B", new string[] { }); } #region GetProjectsThatTransitivelyDependOnThisProject [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestGetProjectsThatTransitivelyDependOnThisProject() { VerifyReverseTransitiveReferences(CreateSolutionFromReferenceMap("A"), "A", new string[] { }); VerifyReverseTransitiveReferences(CreateSolutionFromReferenceMap("B:A A"), "A", new string[] { "B" }); VerifyReverseTransitiveReferences(CreateSolutionFromReferenceMap("C:B B:A A"), "A", new string[] { "B", "C" }); VerifyReverseTransitiveReferences(CreateSolutionFromReferenceMap("C:B B:A A"), "C", new string[] { }); VerifyReverseTransitiveReferences(CreateSolutionFromReferenceMap("D:C,B B:A C A"), "A", new string[] { "D", "B" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestGetProjectsThatTransitivelyDependOnThisProjectThrowsArgumentNull() { var solution = CreateSolutionFromReferenceMap(""); Assert.Throws<ArgumentNullException>("projectId", () => solution.GetProjectDependencyGraph().GetProjectsThatTransitivelyDependOnThisProject(null!)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseTransitiveReferencesIncrementalUpdateInMiddle() { // We are going to create a solution with the references: // // A -> B -> C -> D // // but we will add the B -> C link last, to verify that when we add the B to C link we update the reverse references of D. var solution = CreateSolutionFromReferenceMap("A B C D"); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { }); VerifyReverseTransitiveReferences(solution, "C", new string[] { }); VerifyReverseTransitiveReferences(solution, "D", new string[] { }); solution = AddProjectReferences(solution, "A", new string[] { "B" }); solution = AddProjectReferences(solution, "C", new string[] { "D" }); VerifyDirectReverseReferences(solution, "B", new string[] { "A" }); VerifyDirectReverseReferences(solution, "D", new string[] { "C" }); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); VerifyReverseTransitiveReferences(solution, "C", new string[] { }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "C" }); solution = AddProjectReferences(solution, "B", new string[] { "C" }); VerifyDirectReverseReferences(solution, "C", new string[] { "B" }); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); VerifyReverseTransitiveReferences(solution, "C", new string[] { "A", "B" }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "A", "B", "C" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseTransitiveReferencesForUnrelatedProjectAfterWithProjectReferences() { // We are going to create a solution with the references: // // A -> B C -> D // // and will then remove the reference from C to D. This process will cause us to throw out // all our caches, and asking for the reverse references of A will compute it again. var solution = CreateSolutionFromReferenceMap("A:B B C:D D"); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); VerifyReverseTransitiveReferences(solution, "C", new string[] { }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "C" }); solution = solution.WithProjectReferences(solution.GetProjectsByName("C").Single().Id, SpecializedCollections.EmptyEnumerable<ProjectReference>()); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestForwardReferencesAfterProjectRemoval() { // We are going to create a solution with the references: // // A -> B -> C -> D // // and will then remove project B. var solution = CreateSolutionFromReferenceMap("A:B B:C C:D D"); VerifyDirectReferences(solution, "A", new string[] { "B" }); VerifyDirectReferences(solution, "B", new string[] { "C" }); VerifyDirectReferences(solution, "C", new string[] { "D" }); VerifyDirectReferences(solution, "D", new string[] { }); solution = solution.RemoveProject(solution.GetProjectsByName("B").Single().Id); VerifyDirectReferences(solution, "A", new string[] { }); VerifyDirectReferences(solution, "C", new string[] { "D" }); VerifyDirectReferences(solution, "D", new string[] { }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestForwardTransitiveReferencesAfterProjectRemoval() { // We are going to create a solution with the references: // // A -> B -> C -> D // // and will then remove project B. var solution = CreateSolutionFromReferenceMap("A:B B:C C:D D"); VerifyTransitiveReferences(solution, "A", new string[] { "B", "C", "D" }); VerifyTransitiveReferences(solution, "B", new string[] { "C", "D" }); VerifyTransitiveReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "D", new string[] { }); solution = solution.RemoveProject(solution.GetProjectsByName("B").Single().Id); VerifyTransitiveReferences(solution, "A", new string[] { }); VerifyTransitiveReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "D", new string[] { }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseReferencesAfterProjectRemoval() { // We are going to create a solution with the references: // // A -> B -> C -> D // // and will then remove project B. var solution = CreateSolutionFromReferenceMap("A:B B:C C:D D"); VerifyDirectReverseReferences(solution, "A", new string[] { }); VerifyDirectReverseReferences(solution, "B", new string[] { "A" }); VerifyDirectReverseReferences(solution, "C", new string[] { "B" }); VerifyDirectReverseReferences(solution, "D", new string[] { "C" }); solution = solution.RemoveProject(solution.GetProjectsByName("B").Single().Id); VerifyDirectReverseReferences(solution, "A", new string[] { }); VerifyDirectReverseReferences(solution, "C", new string[] { }); VerifyDirectReverseReferences(solution, "D", new string[] { "C" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseTransitiveReferencesAfterProjectRemoval() { // We are going to create a solution with the references: // // A -> B -> C -> D // // and will then remove project B. var solution = CreateSolutionFromReferenceMap("A:B B:C C:D D"); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); VerifyReverseTransitiveReferences(solution, "C", new string[] { "A", "B" }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "A", "B", "C" }); solution = solution.RemoveProject(solution.GetProjectsByName("B").Single().Id); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "C", new string[] { }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "C" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseTransitiveReferencesAfterProjectReferenceRemoval_PreserveThroughUnrelatedSequence() { // We are going to create a solution with the references: // // A -> B -> C // \ // > D // // and will then remove the project reference A->B. This test verifies that the new project dependency graph // did not lose previously-computed information about the transitive reverse references for D. var solution = CreateSolutionFromReferenceMap("A:B,D B:C C D"); VerifyReverseTransitiveReferences(solution, "D", new string[] { "A" }); var a = solution.GetProjectsByName("A").Single(); var b = solution.GetProjectsByName("B").Single(); var d = solution.GetProjectsByName("D").Single(); var expected = solution.State.GetProjectDependencyGraph().GetProjectsThatTransitivelyDependOnThisProject(d.Id); var aToB = a.ProjectReferences.Single(reference => reference.ProjectId == b.Id); solution = solution.RemoveProjectReference(a.Id, aToB); // Before any other operations, verify that TryGetProjectsThatTransitivelyDependOnThisProject returns a // non-null set. Specifically, it returns the _same_ set that was computed prior to the project reference // removal. Assert.Same(expected, solution.State.GetProjectDependencyGraph().GetTestAccessor().TryGetProjectsThatTransitivelyDependOnThisProject(d.Id)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseTransitiveReferencesAfterProjectReferenceRemoval_PreserveUnrelated() { // We are going to create a solution with the references: // // A -> B -> C // D -> E // // and will then remove the project reference A->B. This test verifies that the new project dependency graph // did not lose previously-computed information about the transitive reverse references for E. var solution = CreateSolutionFromReferenceMap("A:B B:C C D:E E"); VerifyReverseTransitiveReferences(solution, "E", new string[] { "D" }); var a = solution.GetProjectsByName("A").Single(); var b = solution.GetProjectsByName("B").Single(); var e = solution.GetProjectsByName("E").Single(); var expected = solution.State.GetProjectDependencyGraph().GetProjectsThatTransitivelyDependOnThisProject(e.Id); var aToB = a.ProjectReferences.Single(reference => reference.ProjectId == b.Id); solution = solution.RemoveProjectReference(a.Id, aToB); // Before any other operations, verify that TryGetProjectsThatTransitivelyDependOnThisProject returns a // non-null set. Specifically, it returns the _same_ set that was computed prior to the project reference // removal. Assert.Same(expected, solution.State.GetProjectDependencyGraph().GetTestAccessor().TryGetProjectsThatTransitivelyDependOnThisProject(e.Id)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseTransitiveReferencesAfterProjectReferenceRemoval_DiscardImpacted() { // We are going to create a solution with the references: // // A -> B -> C // \ // > D // // and will then remove the project reference A->B. This test verifies that the new project dependency graph // discards previously-computed information about the transitive reverse references for C. var solution = CreateSolutionFromReferenceMap("A:B,D B:C C D"); VerifyReverseTransitiveReferences(solution, "C", new string[] { "A", "B" }); var a = solution.GetProjectsByName("A").Single(); var b = solution.GetProjectsByName("B").Single(); var c = solution.GetProjectsByName("C").Single(); var notExpected = solution.State.GetProjectDependencyGraph().GetProjectsThatTransitivelyDependOnThisProject(c.Id); Assert.NotNull(notExpected); var aToB = a.ProjectReferences.Single(reference => reference.ProjectId == b.Id); solution = solution.RemoveProjectReference(a.Id, aToB); // Before any other operations, verify that TryGetProjectsThatTransitivelyDependOnThisProject returns a // null set. Assert.Null(solution.State.GetProjectDependencyGraph().GetTestAccessor().TryGetProjectsThatTransitivelyDependOnThisProject(c.Id)); VerifyReverseTransitiveReferences(solution, "C", new string[] { "B" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestSameDependencyGraphAfterOneOfMultipleReferencesRemoved() { // We are going to create a solution with the references: // // A -> B -> C -> D // \__^ // // This solution has multiple references from B->C. We will remove one reference from B->C and verify that // the project dependency graph in the solution state did not change (reference equality). // // We then remove the second reference, and verify that the dependency graph does change. var solution = CreateSolutionFromReferenceMap("A:B B:C,C C:D D"); VerifyDirectReferences(solution, "A", new string[] { "B" }); VerifyDirectReferences(solution, "B", new string[] { "C" }); VerifyDirectReferences(solution, "C", new string[] { "D" }); VerifyDirectReferences(solution, "D", new string[] { }); VerifyTransitiveReferences(solution, "A", new string[] { "B", "C", "D" }); VerifyTransitiveReferences(solution, "B", new string[] { "C", "D" }); VerifyTransitiveReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "D", new string[] { }); VerifyDirectReverseReferences(solution, "A", new string[] { }); VerifyDirectReverseReferences(solution, "B", new string[] { "A" }); VerifyDirectReverseReferences(solution, "C", new string[] { "B" }); VerifyDirectReverseReferences(solution, "D", new string[] { "C" }); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); VerifyReverseTransitiveReferences(solution, "C", new string[] { "A", "B" }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "A", "B", "C" }); var dependencyGraph = solution.State.GetProjectDependencyGraph(); Assert.NotNull(dependencyGraph); var b = solution.GetProjectsByName("B").Single(); var c = solution.GetProjectsByName("C").Single(); var firstBToC = b.ProjectReferences.First(reference => reference.ProjectId == c.Id); solution = solution.RemoveProjectReference(b.Id, firstBToC); Assert.Same(dependencyGraph, solution.State.GetProjectDependencyGraph()); b = solution.GetProjectsByName("B").Single(); var remainingBToC = b.ProjectReferences.Single(reference => reference.ProjectId == c.Id); solution = solution.RemoveProjectReference(b.Id, remainingBToC); Assert.NotSame(dependencyGraph, solution.State.GetProjectDependencyGraph()); VerifyDirectReferences(solution, "A", new string[] { "B" }); VerifyDirectReferences(solution, "B", new string[] { }); VerifyDirectReferences(solution, "C", new string[] { "D" }); VerifyDirectReferences(solution, "D", new string[] { }); VerifyTransitiveReferences(solution, "A", new string[] { "B" }); VerifyTransitiveReferences(solution, "B", new string[] { }); VerifyTransitiveReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "D", new string[] { }); VerifyDirectReverseReferences(solution, "A", new string[] { }); VerifyDirectReverseReferences(solution, "B", new string[] { "A" }); VerifyDirectReverseReferences(solution, "C", new string[] { }); VerifyDirectReverseReferences(solution, "D", new string[] { "C" }); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); VerifyReverseTransitiveReferences(solution, "C", new string[] { }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "C" }); } private static void VerifyDirectReverseReferences(Solution solution, string project, string[] expectedResults) { var projectDependencyGraph = solution.GetProjectDependencyGraph(); var projectId = solution.GetProjectsByName(project).Single().Id; var projectIds = projectDependencyGraph.GetProjectsThatDirectlyDependOnThisProject(projectId); var actualResults = projectIds.Select(id => solution.GetRequiredProject(id).Name); Assert.Equal<string>( expectedResults.OrderBy(n => n), actualResults.OrderBy(n => n)); } private static void VerifyReverseTransitiveReferences(Solution solution, string project, string[] expectedResults) { var projectDependencyGraph = solution.GetProjectDependencyGraph(); var projectId = solution.GetProjectsByName(project).Single().Id; var projectIds = projectDependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(projectId); var actualResults = projectIds.Select(id => solution.GetRequiredProject(id).Name); Assert.Equal<string>( expectedResults.OrderBy(n => n), actualResults.OrderBy(n => n)); } #endregion #region Helpers private static Solution CreateSolutionFromReferenceMap(string projectReferences) { var solution = CreateSolution(); var references = new Dictionary<string, IEnumerable<string>>(); var projectDefinitions = projectReferences.Split(' '); foreach (var projectDefinition in projectDefinitions) { var projectDefinitionParts = projectDefinition.Split(':'); string[]? referencedProjectNames = null; if (projectDefinitionParts.Length == 2) { referencedProjectNames = projectDefinitionParts[1].Split(','); } else if (projectDefinitionParts.Length != 1) { throw new ArgumentException("Invalid project definition: " + projectDefinition); } var projectName = projectDefinitionParts[0]; if (referencedProjectNames != null) { references.Add(projectName, referencedProjectNames); } solution = AddProject(solution, projectName); } foreach (var (name, refs) in references) solution = AddProjectReferences(solution, name, refs); return solution; } private static Solution AddProject(Solution solution, string projectName) { var projectId = ProjectId.CreateNewId(debugName: projectName); return solution.AddProject(ProjectInfo.Create(projectId, VersionStamp.Create(), projectName, projectName, LanguageNames.CSharp, projectName)); } private static Solution AddProjectReferences(Solution solution, string projectName, IEnumerable<string> projectReferences) { var referencesByTargetProject = new Dictionary<string, List<ProjectReference>>(); foreach (var targetProject in projectReferences) { var references = referencesByTargetProject.GetOrAdd(targetProject, _ => new List<ProjectReference>()); if (references.Count == 0) { references.Add(new ProjectReference(solution.GetProjectsByName(targetProject).Single().Id)); } else { references.Add(new ProjectReference(solution.GetProjectsByName(targetProject).Single().Id, ImmutableArray.Create($"alias{references.Count}"))); } } return solution.AddProjectReferences( solution.GetProjectsByName(projectName).Single().Id, referencesByTargetProject.SelectMany(pair => pair.Value)); } private static Solution CreateSolution() => new AdhocWorkspace().CurrentSolution; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Host.UnitTests { [UseExportProvider] public class ProjectDependencyGraphTests : TestBase { #region GetTopologicallySortedProjects [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestGetTopologicallySortedProjects() { VerifyTopologicalSort(CreateSolutionFromReferenceMap("A"), "A"); VerifyTopologicalSort(CreateSolutionFromReferenceMap("A B"), "AB", "BA"); VerifyTopologicalSort(CreateSolutionFromReferenceMap("C:A,B B:A A"), "ABC"); VerifyTopologicalSort(CreateSolutionFromReferenceMap("B:A A C:A D:C,B"), "ABCD", "ACBD"); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTopologicallySortedProjectsIncrementalUpdate() { var solution = CreateSolutionFromReferenceMap("A"); VerifyTopologicalSort(solution, "A"); solution = AddProject(solution, "B"); VerifyTopologicalSort(solution, "AB", "BA"); } /// <summary> /// Verifies that <see cref="ProjectDependencyGraph.GetTopologicallySortedProjects(CancellationToken)"/> /// returns one of the correct results. /// </summary> /// <param name="solution"></param> /// <param name="expectedResults">A list of possible results. Because topological sorting is ambiguous /// in that a graph could have multiple topological sorts, this helper lets you give all the possible /// results and it asserts that one of them does match.</param> private static void VerifyTopologicalSort(Solution solution, params string[] expectedResults) { var projectDependencyGraph = solution.GetProjectDependencyGraph(); var projectIds = projectDependencyGraph.GetTopologicallySortedProjects(CancellationToken.None); var actualResult = string.Concat(projectIds.Select(id => solution.GetRequiredProject(id).AssemblyName)); Assert.Contains<string>(actualResult, expectedResults); } #endregion #region Dependency Sets [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] [WorkItem(542438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542438")] public void TestGetDependencySets() { VerifyDependencySets(CreateSolutionFromReferenceMap("A B:A C:A D E:D F:D"), "ABC DEF"); VerifyDependencySets(CreateSolutionFromReferenceMap("A B:A,C C"), "ABC"); VerifyDependencySets(CreateSolutionFromReferenceMap("A B"), "A B"); VerifyDependencySets(CreateSolutionFromReferenceMap("A B C:B"), "A BC"); VerifyDependencySets(CreateSolutionFromReferenceMap("A B:A C:A D:B,C"), "ABCD"); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestDependencySetsIncrementalUpdate() { var solution = CreateSolutionFromReferenceMap("A"); VerifyDependencySets(solution, "A"); solution = AddProject(solution, "B"); VerifyDependencySets(solution, "A B"); } private static void VerifyDependencySets(Solution solution, string expectedResult) { var projectDependencyGraph = solution.GetProjectDependencyGraph(); var projectIds = projectDependencyGraph.GetDependencySets(CancellationToken.None); var actualResult = string.Join(" ", projectIds.Select( group => string.Concat( group.Select(p => solution.GetRequiredProject(p).AssemblyName).OrderBy(n => n))).OrderBy(n => n)); Assert.Equal(expectedResult, actualResult); } #endregion #region GetProjectsThatThisProjectTransitivelyDependsOn [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestGetProjectsThatThisProjectTransitivelyDependsOn() { VerifyTransitiveReferences(CreateSolutionFromReferenceMap("A"), "A", new string[] { }); VerifyTransitiveReferences(CreateSolutionFromReferenceMap("B:A A"), "B", new string[] { "A" }); VerifyTransitiveReferences(CreateSolutionFromReferenceMap("C:B B:A A"), "C", new string[] { "B", "A" }); VerifyTransitiveReferences(CreateSolutionFromReferenceMap("C:B B:A A"), "A", new string[] { }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestGetProjectsThatThisProjectTransitivelyDependsOnThrowsArgumentNull() { var solution = CreateSolutionFromReferenceMap(""); Assert.Throws<ArgumentNullException>("projectId", () => solution.GetProjectDependencyGraph().GetProjectsThatThisProjectDirectlyDependsOn(null!)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTransitiveReferencesIncrementalUpdateInMiddle() { // We are going to create a solution with the references: // // A -> B -> C -> D // // but we will add the B -> C link last, to verify that when we add the B to C link we update the references of A. var solution = CreateSolutionFromReferenceMap("A B C D"); VerifyTransitiveReferences(solution, "A", new string[] { }); VerifyTransitiveReferences(solution, "B", new string[] { }); VerifyTransitiveReferences(solution, "C", new string[] { }); VerifyTransitiveReferences(solution, "D", new string[] { }); solution = AddProjectReferences(solution, "A", new string[] { "B" }); solution = AddProjectReferences(solution, "C", new string[] { "D" }); VerifyDirectReferences(solution, "A", new string[] { "B" }); VerifyDirectReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "A", new string[] { "B" }); VerifyTransitiveReferences(solution, "B", new string[] { }); VerifyTransitiveReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "D", new string[] { }); solution = AddProjectReferences(solution, "B", new string[] { "C" }); VerifyDirectReferences(solution, "B", new string[] { "C" }); VerifyTransitiveReferences(solution, "A", new string[] { "B", "C", "D" }); VerifyTransitiveReferences(solution, "B", new string[] { "C", "D" }); VerifyTransitiveReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "D", new string[] { }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTransitiveReferencesIncrementalUpdateInMiddleLongerChain() { // We are going to create a solution with the references: // // A -> B -> C D -> E -> F // // but we will add the C-> D link last, to verify that when we add the C to D link we update the references of A. This is similar // to the previous test but with a longer chain. var solution = CreateSolutionFromReferenceMap("A:B B:C C D:E E:F F"); VerifyTransitiveReferences(solution, "A", new string[] { "B", "C" }); VerifyTransitiveReferences(solution, "B", new string[] { "C" }); VerifyTransitiveReferences(solution, "D", new string[] { "E", "F" }); VerifyTransitiveReferences(solution, "E", new string[] { "F" }); solution = AddProjectReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "A", new string[] { "B", "C", "D", "E", "F" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTransitiveReferencesIncrementalUpdateWithReferencesAlreadyTransitivelyIncluded() { // We are going to create a solution with the references: // // A -> B -> C // // and then we'll add a reference from A -> C, and transitive references should be different var solution = CreateSolutionFromReferenceMap("A:B B:C C"); void VerifyAllTransitiveReferences() { VerifyTransitiveReferences(solution, "A", new string[] { "B", "C" }); VerifyTransitiveReferences(solution, "B", new string[] { "C" }); VerifyTransitiveReferences(solution, "C", new string[] { }); } VerifyAllTransitiveReferences(); VerifyDirectReferences(solution, "A", new string[] { "B" }); solution = AddProjectReferences(solution, "A", new string[] { "C" }); VerifyAllTransitiveReferences(); VerifyDirectReferences(solution, "A", new string[] { "B", "C" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTransitiveReferencesIncrementalUpdateWithProjectThatHasUnknownReferences() { // We are going to create a solution with the references: // // A B C -> D // // and then we will add a link from A to B. We won't ask for transitive references first, // so we shouldn't have any information for A, B, or C and have to deal with that. var solution = CreateSolutionFromReferenceMap("A B C:D D"); solution = solution.WithProjectReferences(solution.GetProjectsByName("C").Single().Id, SpecializedCollections.EmptyEnumerable<ProjectReference>()); VerifyTransitiveReferences(solution, "A", new string[] { }); // At this point, we know the references for "A" (it's empty), but B and C's are still unknown. // At this point, we're also going to directly use the underlying project graph APIs; // the higher level solution APIs often call and ask for transitive information as well, which makes // this particularly hard to test -- it turns out the data we think is uncomputed might be computed prior // to adding the reference. var dependencyGraph = solution.GetProjectDependencyGraph(); var projectAId = solution.GetProjectsByName("A").Single().Id; var projectBId = solution.GetProjectsByName("B").Single().Id; dependencyGraph = dependencyGraph.WithAdditionalProjectReferences(projectAId, new[] { new ProjectReference(projectBId) }); VerifyTransitiveReferences(solution, dependencyGraph, project: "A", expectedResults: new string[] { "B" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTransitiveReferencesWithDanglingProjectReference() { // We are going to create a solution with the references: // // A -> B // // but we're going to add A as a reference with B not existing yet. Then we'll add in B and ask. var solution = CreateSolution(); var projectAId = ProjectId.CreateNewId("A"); var projectBId = ProjectId.CreateNewId("B"); var projectAInfo = ProjectInfo.Create(projectAId, VersionStamp.Create(), "A", "A", LanguageNames.CSharp, projectReferences: new[] { new ProjectReference(projectBId) }); solution = solution.AddProject(projectAInfo); VerifyDirectReferences(solution, "A", new string[] { }); VerifyTransitiveReferences(solution, "A", new string[] { }); solution = solution.AddProject(projectBId, "B", "B", LanguageNames.CSharp); VerifyTransitiveReferences(solution, "A", new string[] { "B" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestTransitiveReferencesWithMultipleReferences() { // We are going to create a solution with the references: // // A B -> C D -> E // // and then add A referencing B and D in one call, to make sure that works. var solution = CreateSolutionFromReferenceMap("A B:C C D:E E"); VerifyTransitiveReferences(solution, "A", new string[] { }); solution = AddProjectReferences(solution, "A", new string[] { "B", "D" }); VerifyDirectReferences(solution, "A", new string[] { "B", "D" }); VerifyTransitiveReferences(solution, "A", new string[] { "B", "C", "D", "E" }); } private static void VerifyDirectReferences(Solution solution, string project, string[] expectedResults) { var projectDependencyGraph = solution.GetProjectDependencyGraph(); var projectId = solution.GetProjectsByName(project).Single().Id; var projectIds = projectDependencyGraph.GetProjectsThatThisProjectDirectlyDependsOn(projectId); var actualResults = projectIds.Select(id => solution.GetRequiredProject(id).Name); Assert.Equal<string>( expectedResults.OrderBy(n => n), actualResults.OrderBy(n => n)); } private static void VerifyTransitiveReferences(Solution solution, string project, string[] expectedResults) { var projectDependencyGraph = solution.GetProjectDependencyGraph(); VerifyTransitiveReferences(solution, projectDependencyGraph, project, expectedResults); } private static void VerifyTransitiveReferences(Solution solution, ProjectDependencyGraph projectDependencyGraph, string project, string[] expectedResults) { var projectId = solution.GetProjectsByName(project).Single().Id; var projectIds = projectDependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(projectId); var actualResults = projectIds.Select(id => solution.GetRequiredProject(id).Name); Assert.Equal<string>( expectedResults.OrderBy(n => n), actualResults.OrderBy(n => n)); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestDirectAndReverseDirectReferencesAfterWithProjectReferences() { var solution = CreateSolutionFromReferenceMap("A:B B"); VerifyDirectReverseReferences(solution, "B", new string[] { "A" }); solution = solution.WithProjectReferences(solution.GetProjectsByName("A").Single().Id, Enumerable.Empty<ProjectReference>()); VerifyDirectReferences(solution, "A", new string[] { }); VerifyDirectReverseReferences(solution, "B", new string[] { }); } #region GetProjectsThatTransitivelyDependOnThisProject [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestGetProjectsThatTransitivelyDependOnThisProject() { VerifyReverseTransitiveReferences(CreateSolutionFromReferenceMap("A"), "A", new string[] { }); VerifyReverseTransitiveReferences(CreateSolutionFromReferenceMap("B:A A"), "A", new string[] { "B" }); VerifyReverseTransitiveReferences(CreateSolutionFromReferenceMap("C:B B:A A"), "A", new string[] { "B", "C" }); VerifyReverseTransitiveReferences(CreateSolutionFromReferenceMap("C:B B:A A"), "C", new string[] { }); VerifyReverseTransitiveReferences(CreateSolutionFromReferenceMap("D:C,B B:A C A"), "A", new string[] { "D", "B" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestGetProjectsThatTransitivelyDependOnThisProjectThrowsArgumentNull() { var solution = CreateSolutionFromReferenceMap(""); Assert.Throws<ArgumentNullException>("projectId", () => solution.GetProjectDependencyGraph().GetProjectsThatTransitivelyDependOnThisProject(null!)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseTransitiveReferencesIncrementalUpdateInMiddle() { // We are going to create a solution with the references: // // A -> B -> C -> D // // but we will add the B -> C link last, to verify that when we add the B to C link we update the reverse references of D. var solution = CreateSolutionFromReferenceMap("A B C D"); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { }); VerifyReverseTransitiveReferences(solution, "C", new string[] { }); VerifyReverseTransitiveReferences(solution, "D", new string[] { }); solution = AddProjectReferences(solution, "A", new string[] { "B" }); solution = AddProjectReferences(solution, "C", new string[] { "D" }); VerifyDirectReverseReferences(solution, "B", new string[] { "A" }); VerifyDirectReverseReferences(solution, "D", new string[] { "C" }); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); VerifyReverseTransitiveReferences(solution, "C", new string[] { }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "C" }); solution = AddProjectReferences(solution, "B", new string[] { "C" }); VerifyDirectReverseReferences(solution, "C", new string[] { "B" }); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); VerifyReverseTransitiveReferences(solution, "C", new string[] { "A", "B" }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "A", "B", "C" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseTransitiveReferencesForUnrelatedProjectAfterWithProjectReferences() { // We are going to create a solution with the references: // // A -> B C -> D // // and will then remove the reference from C to D. This process will cause us to throw out // all our caches, and asking for the reverse references of A will compute it again. var solution = CreateSolutionFromReferenceMap("A:B B C:D D"); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); VerifyReverseTransitiveReferences(solution, "C", new string[] { }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "C" }); solution = solution.WithProjectReferences(solution.GetProjectsByName("C").Single().Id, SpecializedCollections.EmptyEnumerable<ProjectReference>()); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestForwardReferencesAfterProjectRemoval() { // We are going to create a solution with the references: // // A -> B -> C -> D // // and will then remove project B. var solution = CreateSolutionFromReferenceMap("A:B B:C C:D D"); VerifyDirectReferences(solution, "A", new string[] { "B" }); VerifyDirectReferences(solution, "B", new string[] { "C" }); VerifyDirectReferences(solution, "C", new string[] { "D" }); VerifyDirectReferences(solution, "D", new string[] { }); solution = solution.RemoveProject(solution.GetProjectsByName("B").Single().Id); VerifyDirectReferences(solution, "A", new string[] { }); VerifyDirectReferences(solution, "C", new string[] { "D" }); VerifyDirectReferences(solution, "D", new string[] { }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestForwardTransitiveReferencesAfterProjectRemoval() { // We are going to create a solution with the references: // // A -> B -> C -> D // // and will then remove project B. var solution = CreateSolutionFromReferenceMap("A:B B:C C:D D"); VerifyTransitiveReferences(solution, "A", new string[] { "B", "C", "D" }); VerifyTransitiveReferences(solution, "B", new string[] { "C", "D" }); VerifyTransitiveReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "D", new string[] { }); solution = solution.RemoveProject(solution.GetProjectsByName("B").Single().Id); VerifyTransitiveReferences(solution, "A", new string[] { }); VerifyTransitiveReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "D", new string[] { }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseReferencesAfterProjectRemoval() { // We are going to create a solution with the references: // // A -> B -> C -> D // // and will then remove project B. var solution = CreateSolutionFromReferenceMap("A:B B:C C:D D"); VerifyDirectReverseReferences(solution, "A", new string[] { }); VerifyDirectReverseReferences(solution, "B", new string[] { "A" }); VerifyDirectReverseReferences(solution, "C", new string[] { "B" }); VerifyDirectReverseReferences(solution, "D", new string[] { "C" }); solution = solution.RemoveProject(solution.GetProjectsByName("B").Single().Id); VerifyDirectReverseReferences(solution, "A", new string[] { }); VerifyDirectReverseReferences(solution, "C", new string[] { }); VerifyDirectReverseReferences(solution, "D", new string[] { "C" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseTransitiveReferencesAfterProjectRemoval() { // We are going to create a solution with the references: // // A -> B -> C -> D // // and will then remove project B. var solution = CreateSolutionFromReferenceMap("A:B B:C C:D D"); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); VerifyReverseTransitiveReferences(solution, "C", new string[] { "A", "B" }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "A", "B", "C" }); solution = solution.RemoveProject(solution.GetProjectsByName("B").Single().Id); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "C", new string[] { }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "C" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseTransitiveReferencesAfterProjectReferenceRemoval_PreserveThroughUnrelatedSequence() { // We are going to create a solution with the references: // // A -> B -> C // \ // > D // // and will then remove the project reference A->B. This test verifies that the new project dependency graph // did not lose previously-computed information about the transitive reverse references for D. var solution = CreateSolutionFromReferenceMap("A:B,D B:C C D"); VerifyReverseTransitiveReferences(solution, "D", new string[] { "A" }); var a = solution.GetProjectsByName("A").Single(); var b = solution.GetProjectsByName("B").Single(); var d = solution.GetProjectsByName("D").Single(); var expected = solution.State.GetProjectDependencyGraph().GetProjectsThatTransitivelyDependOnThisProject(d.Id); var aToB = a.ProjectReferences.Single(reference => reference.ProjectId == b.Id); solution = solution.RemoveProjectReference(a.Id, aToB); // Before any other operations, verify that TryGetProjectsThatTransitivelyDependOnThisProject returns a // non-null set. Specifically, it returns the _same_ set that was computed prior to the project reference // removal. Assert.Same(expected, solution.State.GetProjectDependencyGraph().GetTestAccessor().TryGetProjectsThatTransitivelyDependOnThisProject(d.Id)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseTransitiveReferencesAfterProjectReferenceRemoval_PreserveUnrelated() { // We are going to create a solution with the references: // // A -> B -> C // D -> E // // and will then remove the project reference A->B. This test verifies that the new project dependency graph // did not lose previously-computed information about the transitive reverse references for E. var solution = CreateSolutionFromReferenceMap("A:B B:C C D:E E"); VerifyReverseTransitiveReferences(solution, "E", new string[] { "D" }); var a = solution.GetProjectsByName("A").Single(); var b = solution.GetProjectsByName("B").Single(); var e = solution.GetProjectsByName("E").Single(); var expected = solution.State.GetProjectDependencyGraph().GetProjectsThatTransitivelyDependOnThisProject(e.Id); var aToB = a.ProjectReferences.Single(reference => reference.ProjectId == b.Id); solution = solution.RemoveProjectReference(a.Id, aToB); // Before any other operations, verify that TryGetProjectsThatTransitivelyDependOnThisProject returns a // non-null set. Specifically, it returns the _same_ set that was computed prior to the project reference // removal. Assert.Same(expected, solution.State.GetProjectDependencyGraph().GetTestAccessor().TryGetProjectsThatTransitivelyDependOnThisProject(e.Id)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestReverseTransitiveReferencesAfterProjectReferenceRemoval_DiscardImpacted() { // We are going to create a solution with the references: // // A -> B -> C // \ // > D // // and will then remove the project reference A->B. This test verifies that the new project dependency graph // discards previously-computed information about the transitive reverse references for C. var solution = CreateSolutionFromReferenceMap("A:B,D B:C C D"); VerifyReverseTransitiveReferences(solution, "C", new string[] { "A", "B" }); var a = solution.GetProjectsByName("A").Single(); var b = solution.GetProjectsByName("B").Single(); var c = solution.GetProjectsByName("C").Single(); var notExpected = solution.State.GetProjectDependencyGraph().GetProjectsThatTransitivelyDependOnThisProject(c.Id); Assert.NotNull(notExpected); var aToB = a.ProjectReferences.Single(reference => reference.ProjectId == b.Id); solution = solution.RemoveProjectReference(a.Id, aToB); // Before any other operations, verify that TryGetProjectsThatTransitivelyDependOnThisProject returns a // null set. Assert.Null(solution.State.GetProjectDependencyGraph().GetTestAccessor().TryGetProjectsThatTransitivelyDependOnThisProject(c.Id)); VerifyReverseTransitiveReferences(solution, "C", new string[] { "B" }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestSameDependencyGraphAfterOneOfMultipleReferencesRemoved() { // We are going to create a solution with the references: // // A -> B -> C -> D // \__^ // // This solution has multiple references from B->C. We will remove one reference from B->C and verify that // the project dependency graph in the solution state did not change (reference equality). // // We then remove the second reference, and verify that the dependency graph does change. var solution = CreateSolutionFromReferenceMap("A:B B:C,C C:D D"); VerifyDirectReferences(solution, "A", new string[] { "B" }); VerifyDirectReferences(solution, "B", new string[] { "C" }); VerifyDirectReferences(solution, "C", new string[] { "D" }); VerifyDirectReferences(solution, "D", new string[] { }); VerifyTransitiveReferences(solution, "A", new string[] { "B", "C", "D" }); VerifyTransitiveReferences(solution, "B", new string[] { "C", "D" }); VerifyTransitiveReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "D", new string[] { }); VerifyDirectReverseReferences(solution, "A", new string[] { }); VerifyDirectReverseReferences(solution, "B", new string[] { "A" }); VerifyDirectReverseReferences(solution, "C", new string[] { "B" }); VerifyDirectReverseReferences(solution, "D", new string[] { "C" }); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); VerifyReverseTransitiveReferences(solution, "C", new string[] { "A", "B" }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "A", "B", "C" }); var dependencyGraph = solution.State.GetProjectDependencyGraph(); Assert.NotNull(dependencyGraph); var b = solution.GetProjectsByName("B").Single(); var c = solution.GetProjectsByName("C").Single(); var firstBToC = b.ProjectReferences.First(reference => reference.ProjectId == c.Id); solution = solution.RemoveProjectReference(b.Id, firstBToC); Assert.Same(dependencyGraph, solution.State.GetProjectDependencyGraph()); b = solution.GetProjectsByName("B").Single(); var remainingBToC = b.ProjectReferences.Single(reference => reference.ProjectId == c.Id); solution = solution.RemoveProjectReference(b.Id, remainingBToC); Assert.NotSame(dependencyGraph, solution.State.GetProjectDependencyGraph()); VerifyDirectReferences(solution, "A", new string[] { "B" }); VerifyDirectReferences(solution, "B", new string[] { }); VerifyDirectReferences(solution, "C", new string[] { "D" }); VerifyDirectReferences(solution, "D", new string[] { }); VerifyTransitiveReferences(solution, "A", new string[] { "B" }); VerifyTransitiveReferences(solution, "B", new string[] { }); VerifyTransitiveReferences(solution, "C", new string[] { "D" }); VerifyTransitiveReferences(solution, "D", new string[] { }); VerifyDirectReverseReferences(solution, "A", new string[] { }); VerifyDirectReverseReferences(solution, "B", new string[] { "A" }); VerifyDirectReverseReferences(solution, "C", new string[] { }); VerifyDirectReverseReferences(solution, "D", new string[] { "C" }); VerifyReverseTransitiveReferences(solution, "A", new string[] { }); VerifyReverseTransitiveReferences(solution, "B", new string[] { "A" }); VerifyReverseTransitiveReferences(solution, "C", new string[] { }); VerifyReverseTransitiveReferences(solution, "D", new string[] { "C" }); } private static void VerifyDirectReverseReferences(Solution solution, string project, string[] expectedResults) { var projectDependencyGraph = solution.GetProjectDependencyGraph(); var projectId = solution.GetProjectsByName(project).Single().Id; var projectIds = projectDependencyGraph.GetProjectsThatDirectlyDependOnThisProject(projectId); var actualResults = projectIds.Select(id => solution.GetRequiredProject(id).Name); Assert.Equal<string>( expectedResults.OrderBy(n => n), actualResults.OrderBy(n => n)); } private static void VerifyReverseTransitiveReferences(Solution solution, string project, string[] expectedResults) { var projectDependencyGraph = solution.GetProjectDependencyGraph(); var projectId = solution.GetProjectsByName(project).Single().Id; var projectIds = projectDependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(projectId); var actualResults = projectIds.Select(id => solution.GetRequiredProject(id).Name); Assert.Equal<string>( expectedResults.OrderBy(n => n), actualResults.OrderBy(n => n)); } #endregion #region Helpers private static Solution CreateSolutionFromReferenceMap(string projectReferences) { var solution = CreateSolution(); var references = new Dictionary<string, IEnumerable<string>>(); var projectDefinitions = projectReferences.Split(' '); foreach (var projectDefinition in projectDefinitions) { var projectDefinitionParts = projectDefinition.Split(':'); string[]? referencedProjectNames = null; if (projectDefinitionParts.Length == 2) { referencedProjectNames = projectDefinitionParts[1].Split(','); } else if (projectDefinitionParts.Length != 1) { throw new ArgumentException("Invalid project definition: " + projectDefinition); } var projectName = projectDefinitionParts[0]; if (referencedProjectNames != null) { references.Add(projectName, referencedProjectNames); } solution = AddProject(solution, projectName); } foreach (var (name, refs) in references) solution = AddProjectReferences(solution, name, refs); return solution; } private static Solution AddProject(Solution solution, string projectName) { var projectId = ProjectId.CreateNewId(debugName: projectName); return solution.AddProject(ProjectInfo.Create(projectId, VersionStamp.Create(), projectName, projectName, LanguageNames.CSharp, projectName)); } private static Solution AddProjectReferences(Solution solution, string projectName, IEnumerable<string> projectReferences) { var referencesByTargetProject = new Dictionary<string, List<ProjectReference>>(); foreach (var targetProject in projectReferences) { var references = referencesByTargetProject.GetOrAdd(targetProject, _ => new List<ProjectReference>()); if (references.Count == 0) { references.Add(new ProjectReference(solution.GetProjectsByName(targetProject).Single().Id)); } else { references.Add(new ProjectReference(solution.GetProjectsByName(targetProject).Single().Id, ImmutableArray.Create($"alias{references.Count}"))); } } return solution.AddProjectReferences( solution.GetProjectsByName(projectName).Single().Id, referencesByTargetProject.SelectMany(pair => pair.Value)); } private static Solution CreateSolution() => new AdhocWorkspace().CurrentSolution; #endregion } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedParameter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedParameter : Cci.IParameterDefinition { public readonly CommonEmbeddedMember ContainingPropertyOrMethod; public readonly TParameterSymbol UnderlyingParameter; private ImmutableArray<TAttributeData> _lazyAttributes; protected CommonEmbeddedParameter(CommonEmbeddedMember containingPropertyOrMethod, TParameterSymbol underlyingParameter) { this.ContainingPropertyOrMethod = containingPropertyOrMethod; this.UnderlyingParameter = underlyingParameter; } protected TEmbeddedTypesManager TypeManager { get { return ContainingPropertyOrMethod.TypeManager; } } protected abstract bool HasDefaultValue { get; } protected abstract MetadataConstant GetDefaultValue(EmitContext context); protected abstract bool IsIn { get; } protected abstract bool IsOut { get; } protected abstract bool IsOptional { get; } protected abstract bool IsMarshalledExplicitly { get; } protected abstract Cci.IMarshallingInformation MarshallingInformation { get; } protected abstract ImmutableArray<byte> MarshallingDescriptor { get; } protected abstract string Name { get; } protected abstract Cci.IParameterTypeInformation UnderlyingParameterTypeInformation { get; } protected abstract ushort Index { get; } protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); private bool IsTargetAttribute(TAttributeData attrData, AttributeDescription description) { return TypeManager.IsTargetAttribute(UnderlyingParameter, attrData, description); } private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var builder = ArrayBuilder<TAttributeData>.GetInstance(); // Copy some of the attributes. // Note, when porting attributes, we are not using constructors from original symbol. // The constructors might be missing (for example, in metadata case) and doing lookup // will ensure that we report appropriate errors. foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder)) { if (IsTargetAttribute(attrData, AttributeDescription.ParamArrayAttribute)) { if (attrData.CommonConstructorArguments.Length == 0) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else if (IsTargetAttribute(attrData, AttributeDescription.DateTimeConstantAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else { int signatureIndex = TypeManager.GetTargetAttributeSignatureIndex(UnderlyingParameter, attrData, AttributeDescription.DecimalConstantAttribute); if (signatureIndex != -1) { Debug.Assert(signatureIndex == 0 || signatureIndex == 1); if (attrData.CommonConstructorArguments.Length == 5) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute( signatureIndex == 0 ? WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor : WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32, attrData, syntaxNodeOpt, diagnostics)); } } else if (IsTargetAttribute(attrData, AttributeDescription.DefaultParameterValueAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } } } return builder.ToImmutableAndFree(); } bool Cci.IParameterDefinition.HasDefaultValue { get { return HasDefaultValue; } } MetadataConstant Cci.IParameterDefinition.GetDefaultValue(EmitContext context) { return GetDefaultValue(context); } bool Cci.IParameterDefinition.IsIn { get { return IsIn; } } bool Cci.IParameterDefinition.IsOut { get { return IsOut; } } bool Cci.IParameterDefinition.IsOptional { get { return IsOptional; } } bool Cci.IParameterDefinition.IsMarshalledExplicitly { get { return IsMarshalledExplicitly; } } Cci.IMarshallingInformation Cci.IParameterDefinition.MarshallingInformation { get { return MarshallingInformation; } } ImmutableArray<byte> Cci.IParameterDefinition.MarshallingDescriptor { get { return MarshallingDescriptor; } } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { if (_lazyAttributes.IsDefault) { var diagnostics = DiagnosticBag.GetInstance(); var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) { // Save any diagnostics that we encountered. context.Diagnostics.AddRange(diagnostics); } diagnostics.Free(); } return _lazyAttributes; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { throw ExceptionUtilities.Unreachable; } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return this; } CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name { get { return Name; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.CustomModifiers { get { return UnderlyingParameterTypeInformation.CustomModifiers; } } bool Cci.IParameterTypeInformation.IsByReference { get { return UnderlyingParameterTypeInformation.IsByReference; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.RefCustomModifiers { get { return UnderlyingParameterTypeInformation.RefCustomModifiers; } } Cci.ITypeReference Cci.IParameterTypeInformation.GetType(EmitContext context) { return UnderlyingParameterTypeInformation.GetType(context); } ushort Cci.IParameterListEntry.Index { get { return Index; } } /// <remarks> /// This is only used for testing. /// </remarks> public override string ToString() { return ((ISymbol)UnderlyingParameter).ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedParameter : Cci.IParameterDefinition { public readonly CommonEmbeddedMember ContainingPropertyOrMethod; public readonly TParameterSymbol UnderlyingParameter; private ImmutableArray<TAttributeData> _lazyAttributes; protected CommonEmbeddedParameter(CommonEmbeddedMember containingPropertyOrMethod, TParameterSymbol underlyingParameter) { this.ContainingPropertyOrMethod = containingPropertyOrMethod; this.UnderlyingParameter = underlyingParameter; } protected TEmbeddedTypesManager TypeManager { get { return ContainingPropertyOrMethod.TypeManager; } } protected abstract bool HasDefaultValue { get; } protected abstract MetadataConstant GetDefaultValue(EmitContext context); protected abstract bool IsIn { get; } protected abstract bool IsOut { get; } protected abstract bool IsOptional { get; } protected abstract bool IsMarshalledExplicitly { get; } protected abstract Cci.IMarshallingInformation MarshallingInformation { get; } protected abstract ImmutableArray<byte> MarshallingDescriptor { get; } protected abstract string Name { get; } protected abstract Cci.IParameterTypeInformation UnderlyingParameterTypeInformation { get; } protected abstract ushort Index { get; } protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); private bool IsTargetAttribute(TAttributeData attrData, AttributeDescription description) { return TypeManager.IsTargetAttribute(UnderlyingParameter, attrData, description); } private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var builder = ArrayBuilder<TAttributeData>.GetInstance(); // Copy some of the attributes. // Note, when porting attributes, we are not using constructors from original symbol. // The constructors might be missing (for example, in metadata case) and doing lookup // will ensure that we report appropriate errors. foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder)) { if (IsTargetAttribute(attrData, AttributeDescription.ParamArrayAttribute)) { if (attrData.CommonConstructorArguments.Length == 0) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else if (IsTargetAttribute(attrData, AttributeDescription.DateTimeConstantAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else { int signatureIndex = TypeManager.GetTargetAttributeSignatureIndex(UnderlyingParameter, attrData, AttributeDescription.DecimalConstantAttribute); if (signatureIndex != -1) { Debug.Assert(signatureIndex == 0 || signatureIndex == 1); if (attrData.CommonConstructorArguments.Length == 5) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute( signatureIndex == 0 ? WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor : WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32, attrData, syntaxNodeOpt, diagnostics)); } } else if (IsTargetAttribute(attrData, AttributeDescription.DefaultParameterValueAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } } } return builder.ToImmutableAndFree(); } bool Cci.IParameterDefinition.HasDefaultValue { get { return HasDefaultValue; } } MetadataConstant Cci.IParameterDefinition.GetDefaultValue(EmitContext context) { return GetDefaultValue(context); } bool Cci.IParameterDefinition.IsIn { get { return IsIn; } } bool Cci.IParameterDefinition.IsOut { get { return IsOut; } } bool Cci.IParameterDefinition.IsOptional { get { return IsOptional; } } bool Cci.IParameterDefinition.IsMarshalledExplicitly { get { return IsMarshalledExplicitly; } } Cci.IMarshallingInformation Cci.IParameterDefinition.MarshallingInformation { get { return MarshallingInformation; } } ImmutableArray<byte> Cci.IParameterDefinition.MarshallingDescriptor { get { return MarshallingDescriptor; } } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { if (_lazyAttributes.IsDefault) { var diagnostics = DiagnosticBag.GetInstance(); var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) { // Save any diagnostics that we encountered. context.Diagnostics.AddRange(diagnostics); } diagnostics.Free(); } return _lazyAttributes; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { throw ExceptionUtilities.Unreachable; } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return this; } CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name { get { return Name; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.CustomModifiers { get { return UnderlyingParameterTypeInformation.CustomModifiers; } } bool Cci.IParameterTypeInformation.IsByReference { get { return UnderlyingParameterTypeInformation.IsByReference; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.RefCustomModifiers { get { return UnderlyingParameterTypeInformation.RefCustomModifiers; } } Cci.ITypeReference Cci.IParameterTypeInformation.GetType(EmitContext context) { return UnderlyingParameterTypeInformation.GetType(context); } ushort Cci.IParameterListEntry.Index { get { return Index; } } /// <remarks> /// This is only used for testing. /// </remarks> public override string ToString() { return ((ISymbol)UnderlyingParameter).ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/EditorFeatures/CSharpTest2/Recommendations/DecimalKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DecimalKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumBaseTypes() { await VerifyAbsenceAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInImplicitOperator() { await VerifyKeywordAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExplicitOperator() { await VerifyKeywordAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInChecked() { await VerifyKeywordAsync(AddInsideMethod( @"var a = checked($$")); } [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnchecked() { await VerifyKeywordAsync(AddInsideMethod( @"var a = unchecked($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContext() { await VerifyKeywordAsync(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContextNotAfterDot() { await VerifyAbsenceAsync(@" /// <see cref=""System.$$"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncAsType() => await VerifyKeywordAsync(@"class c { async async $$ }"); [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCrefTypeParameter() { await VerifyAbsenceAsync(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { Helper($$) } static void Helper(decimal x) { } } "); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinType() { await VerifyKeywordAsync(@" class Program { ($$ }"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinMember() { await VerifyKeywordAsync(@" class Program { void Method() { ($$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(AddInsideMethod($@" {keyword} $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DecimalKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumBaseTypes() { await VerifyAbsenceAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInImplicitOperator() { await VerifyKeywordAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExplicitOperator() { await VerifyKeywordAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInChecked() { await VerifyKeywordAsync(AddInsideMethod( @"var a = checked($$")); } [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnchecked() { await VerifyKeywordAsync(AddInsideMethod( @"var a = unchecked($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContext() { await VerifyKeywordAsync(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContextNotAfterDot() { await VerifyAbsenceAsync(@" /// <see cref=""System.$$"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncAsType() => await VerifyKeywordAsync(@"class c { async async $$ }"); [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCrefTypeParameter() { await VerifyAbsenceAsync(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { Helper($$) } static void Helper(decimal x) { } } "); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinType() { await VerifyKeywordAsync(@" class Program { ($$ }"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinMember() { await VerifyKeywordAsync(@" class Program { void Method() { ($$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(AddInsideMethod($@" {keyword} $$")); } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./eng/common/templates/jobs/source-build.yml
parameters: # This template adds arcade-powered source-build to CI. A job is created for each platform, as # well as an optional server job that completes when all platform jobs complete. # The name of the "join" job for all source-build platforms. If set to empty string, the job is # not included. Existing repo pipelines can use this job depend on all source-build jobs # completing without maintaining a separate list of every single job ID: just depend on this one # server job. By default, not included. Recommended name if used: 'Source_Build_Complete'. allCompletedJobId: '' # See /eng/common/templates/job/source-build.yml jobNamePrefix: 'Source_Build' # This is the default platform provided by Arcade, intended for use by a managed-only repo. defaultManagedPlatform: name: 'Managed' container: 'mcr.microsoft.com/dotnet-buildtools/prereqs:centos-7-3e800f1-20190501005343' # Defines the platforms on which to run build jobs. One job is created for each platform, and the # object in this array is sent to the job template as 'platform'. If no platforms are specified, # one job runs on 'defaultManagedPlatform'. platforms: [] jobs: - ${{ if ne(parameters.allCompletedJobId, '') }}: - job: ${{ parameters.allCompletedJobId }} displayName: Source-Build Complete pool: server dependsOn: - ${{ each platform in parameters.platforms }}: - ${{ parameters.jobNamePrefix }}_${{ platform.name }} - ${{ if eq(length(parameters.platforms), 0) }}: - ${{ parameters.jobNamePrefix }}_${{ parameters.defaultManagedPlatform.name }} - ${{ each platform in parameters.platforms }}: - template: /eng/common/templates/job/source-build.yml parameters: jobNamePrefix: ${{ parameters.jobNamePrefix }} platform: ${{ platform }} - ${{ if eq(length(parameters.platforms), 0) }}: - template: /eng/common/templates/job/source-build.yml parameters: jobNamePrefix: ${{ parameters.jobNamePrefix }} platform: ${{ parameters.defaultManagedPlatform }}
parameters: # This template adds arcade-powered source-build to CI. A job is created for each platform, as # well as an optional server job that completes when all platform jobs complete. # The name of the "join" job for all source-build platforms. If set to empty string, the job is # not included. Existing repo pipelines can use this job depend on all source-build jobs # completing without maintaining a separate list of every single job ID: just depend on this one # server job. By default, not included. Recommended name if used: 'Source_Build_Complete'. allCompletedJobId: '' # See /eng/common/templates/job/source-build.yml jobNamePrefix: 'Source_Build' # This is the default platform provided by Arcade, intended for use by a managed-only repo. defaultManagedPlatform: name: 'Managed' container: 'mcr.microsoft.com/dotnet-buildtools/prereqs:centos-7-3e800f1-20190501005343' # Defines the platforms on which to run build jobs. One job is created for each platform, and the # object in this array is sent to the job template as 'platform'. If no platforms are specified, # one job runs on 'defaultManagedPlatform'. platforms: [] jobs: - ${{ if ne(parameters.allCompletedJobId, '') }}: - job: ${{ parameters.allCompletedJobId }} displayName: Source-Build Complete pool: server dependsOn: - ${{ each platform in parameters.platforms }}: - ${{ parameters.jobNamePrefix }}_${{ platform.name }} - ${{ if eq(length(parameters.platforms), 0) }}: - ${{ parameters.jobNamePrefix }}_${{ parameters.defaultManagedPlatform.name }} - ${{ each platform in parameters.platforms }}: - template: /eng/common/templates/job/source-build.yml parameters: jobNamePrefix: ${{ parameters.jobNamePrefix }} platform: ${{ platform }} - ${{ if eq(length(parameters.platforms), 0) }}: - template: /eng/common/templates/job/source-build.yml parameters: jobNamePrefix: ${{ parameters.jobNamePrefix }} platform: ${{ parameters.defaultManagedPlatform }}
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a type other than an array, a pointer, a type parameter, and dynamic. /// </summary> internal abstract partial class NamedTypeSymbol : TypeSymbol, INamedTypeSymbolInternal { private bool _hasNoBaseCycles; // Only the compiler can create NamedTypeSymbols. internal NamedTypeSymbol(TupleExtraData tupleData = null) { _lazyTupleData = tupleData; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO: How should anonymous types be represented? One possible options: have an // IsAnonymous on this type. The Name would then return a unique compiler-generated // type that matches the metadata name. /// <summary> /// Returns the arity of this type, or the number of type parameters it takes. /// A non-generic type has zero arity. /// </summary> public abstract int Arity { get; } /// <summary> /// Returns the type parameters that this type has. If this is a non-generic type, /// returns an empty ImmutableArray. /// </summary> public abstract ImmutableArray<TypeParameterSymbol> TypeParameters { get; } /// <summary> /// Returns the type arguments that have been substituted for the type parameters. /// If nothing has been substituted for a give type parameters, /// then the type parameter itself is consider the type argument. /// </summary> internal abstract ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get; } internal ImmutableArray<TypeWithAnnotations> TypeArgumentsWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; foreach (var typeArgument in result) { typeArgument.Type.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } internal TypeWithAnnotations TypeArgumentWithDefinitionUseSiteDiagnostics(int index, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[index]; result.Type.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); return result; } /// <summary> /// Returns the type symbol that this type was constructed from. This type symbol /// has the same containing type (if any), but has type arguments that are the same /// as the type parameters (although its containing type might not). /// </summary> public abstract NamedTypeSymbol ConstructedFrom { get; } /// <summary> /// For enum types, gets the underlying type. Returns null on all other /// kinds of types. /// </summary> public virtual NamedTypeSymbol EnumUnderlyingType { get { return null; } } public override NamedTypeSymbol ContainingType { get { // we can do this since if a type does not live directly in a type // there is no containing type at all // NOTE: many derived types will override this with even better implementation // since most know their containing types/symbols directly return this.ContainingSymbol as NamedTypeSymbol; } } /// <summary> /// Returns true for a struct type containing a cycle. /// This property is intended for flow analysis only /// since it is only implemented for source types. /// </summary> internal virtual bool KnownCircularStruct { get { return false; } } internal bool KnownToHaveNoDeclaredBaseCycles { get { return _hasNoBaseCycles; } } internal void SetKnownToHaveNoDeclaredBaseCycles() { _hasNoBaseCycles = true; } /// <summary> /// Is this a NoPia local type explicitly declared in source, i.e. /// top level type with a TypeIdentifier attribute on it? /// </summary> internal virtual bool IsExplicitDefinitionOfNoPiaLocalType { get { return false; } } /// <summary> /// Returns true and a string from the first GuidAttribute on the type, /// the string might be null or an invalid guid representation. False, /// if there is no GuidAttribute with string argument. /// </summary> internal virtual bool GetGuidString(out string guidString) { return GetGuidStringDefaultImplementation(out guidString); } #nullable enable /// <summary> /// For delegate types, gets the delegate's invoke method. Returns null on /// all other kinds of types. Note that it is possible to have an ill-formed /// delegate type imported from metadata which does not have an Invoke method. /// Such a type will be classified as a delegate but its DelegateInvokeMethod /// would be null. /// </summary> public MethodSymbol? DelegateInvokeMethod { get { if (TypeKind != TypeKind.Delegate) { return null; } var methods = GetMembers(WellKnownMemberNames.DelegateInvokeName); if (methods.Length != 1) { return null; } var method = methods[0] as MethodSymbol; //EDMAURER we used to also check 'method.IsVirtual' because section 13.6 //of the CLI spec dictates that it be virtual, but real world //working metadata has been found that contains an Invoke method that is //marked as virtual but not newslot (both of those must be combined to //meet the C# definition of virtual). Rather than weaken the check //I've removed it, as the Dev10 compiler makes no check, and we don't //stand to gain anything by having it. //return method != null && method.IsVirtual ? method : null; return method; } } #nullable disable /// <summary> /// Get the operators for this type by their metadata name /// </summary> internal ImmutableArray<MethodSymbol> GetOperators(string name) { ImmutableArray<Symbol> candidates = GetSimpleNonTypeMembers(name); if (candidates.IsEmpty) { return ImmutableArray<MethodSymbol>.Empty; } ArrayBuilder<MethodSymbol> operators = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (MethodSymbol candidate in candidates.OfType<MethodSymbol>()) { if (candidate.MethodKind == MethodKind.UserDefinedOperator || candidate.MethodKind == MethodKind.Conversion) { operators.Add(candidate); } } return operators.ToImmutableAndFree(); } /// <summary> /// Get the instance constructors for this type. /// </summary> public ImmutableArray<MethodSymbol> InstanceConstructors { get { return GetConstructors(includeInstance: true, includeStatic: false); } } /// <summary> /// Get the static constructors for this type. /// </summary> public ImmutableArray<MethodSymbol> StaticConstructors { get { return GetConstructors(includeInstance: false, includeStatic: true); } } /// <summary> /// Get the instance and static constructors for this type. /// </summary> public ImmutableArray<MethodSymbol> Constructors { get { return GetConstructors(includeInstance: true, includeStatic: true); } } private ImmutableArray<MethodSymbol> GetConstructors(bool includeInstance, bool includeStatic) { Debug.Assert(includeInstance || includeStatic); ImmutableArray<Symbol> instanceCandidates = includeInstance ? GetMembers(WellKnownMemberNames.InstanceConstructorName) : ImmutableArray<Symbol>.Empty; ImmutableArray<Symbol> staticCandidates = includeStatic ? GetMembers(WellKnownMemberNames.StaticConstructorName) : ImmutableArray<Symbol>.Empty; if (instanceCandidates.IsEmpty && staticCandidates.IsEmpty) { return ImmutableArray<MethodSymbol>.Empty; } ArrayBuilder<MethodSymbol> constructors = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (Symbol candidate in instanceCandidates) { if (candidate is MethodSymbol method) { Debug.Assert(method.MethodKind == MethodKind.Constructor); constructors.Add(method); } } foreach (Symbol candidate in staticCandidates) { if (candidate is MethodSymbol method) { Debug.Assert(method.MethodKind == MethodKind.StaticConstructor); constructors.Add(method); } } return constructors.ToImmutableAndFree(); } /// <summary> /// Get the indexers for this type. /// </summary> /// <remarks> /// Won't include indexers that are explicit interface implementations. /// </remarks> public ImmutableArray<PropertySymbol> Indexers { get { ImmutableArray<Symbol> candidates = GetSimpleNonTypeMembers(WellKnownMemberNames.Indexer); if (candidates.IsEmpty) { return ImmutableArray<PropertySymbol>.Empty; } // The common case will be returning a list with the same elements as "candidates", // but we need a list of PropertySymbols, so we're stuck building a new list anyway. ArrayBuilder<PropertySymbol> indexers = ArrayBuilder<PropertySymbol>.GetInstance(); foreach (Symbol candidate in candidates) { if (candidate.Kind == SymbolKind.Property) { Debug.Assert(((PropertySymbol)candidate).IsIndexer); indexers.Add((PropertySymbol)candidate); } } return indexers.ToImmutableAndFree(); } } /// <summary> /// Returns true if this type might contain extension methods. If this property /// returns false, there are no extension methods in this type. /// </summary> /// <remarks> /// This property allows the search for extension methods to be narrowed quickly. /// </remarks> public abstract bool MightContainExtensionMethods { get; } internal void GetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { if (this.MightContainExtensionMethods) { DoGetExtensionMethods(methods, nameOpt, arity, options); } } internal void DoGetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { var members = nameOpt == null ? this.GetMembersUnordered() : this.GetSimpleNonTypeMembers(nameOpt); foreach (var member in members) { if (member.Kind == SymbolKind.Method) { var method = (MethodSymbol)member; if (method.IsExtensionMethod && ((options & LookupOptions.AllMethodsOnArityZero) != 0 || arity == method.Arity)) { var thisParam = method.Parameters.First(); if ((thisParam.RefKind == RefKind.Ref && !thisParam.Type.IsValueType) || (thisParam.RefKind == RefKind.In && thisParam.Type.TypeKind != TypeKind.Struct)) { // For ref and ref-readonly extension methods, receivers need to be of the correct types to be considered in lookup continue; } Debug.Assert(method.MethodKind != MethodKind.ReducedExtension); methods.Add(method); } } } } // TODO: Probably should provide similar accessors for static constructor, destructor, // TODO: operators, conversions. /// <summary> /// Returns true if this type is known to be a reference type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public override bool IsReferenceType { get { var kind = TypeKind; return kind != TypeKind.Enum && kind != TypeKind.Struct && kind != TypeKind.Error; } } /// <summary> /// Returns true if this type is known to be a value type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public override bool IsValueType { get { var kind = TypeKind; return kind == TypeKind.Struct || kind == TypeKind.Enum; } } internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // CONSIDER: we could cache this, but it's only expensive for non-special struct types // that are pointed to. For now, only cache on SourceMemberContainerSymbol since it fits // nicely into the flags variable. return BaseTypeAnalysis.GetManagedKind(this, ref useSiteInfo); } /// <summary> /// Gets the associated attribute usage info for an attribute type. /// </summary> internal abstract AttributeUsageInfo GetAttributeUsageInfo(); /// <summary> /// Returns true if the type is a Script class. /// It might be an interactive submission class or a Script class in a csx file. /// </summary> public virtual bool IsScriptClass { get { return false; } } internal bool IsSubmissionClass { get { return TypeKind == TypeKind.Submission; } } internal SynthesizedInstanceConstructor GetScriptConstructor() { Debug.Assert(IsScriptClass); return (SynthesizedInstanceConstructor)InstanceConstructors.Single(); } internal SynthesizedInteractiveInitializerMethod GetScriptInitializer() { Debug.Assert(IsScriptClass); return (SynthesizedInteractiveInitializerMethod)GetMembers(SynthesizedInteractiveInitializerMethod.InitializerName).Single(); } internal SynthesizedEntryPointSymbol GetScriptEntryPoint() { Debug.Assert(IsScriptClass); var name = (TypeKind == TypeKind.Submission) ? SynthesizedEntryPointSymbol.FactoryName : SynthesizedEntryPointSymbol.MainName; return (SynthesizedEntryPointSymbol)GetMembers(name).Single(); } /// <summary> /// Returns true if the type is the implicit class that holds onto invalid global members (like methods or /// statements in a non script file). /// </summary> public virtual bool IsImplicitClass { get { return false; } } /// <summary> /// Gets the name of this symbol. Symbols without a name return the empty string; null is /// never returned. /// </summary> public abstract override string Name { get; } /// <summary> /// Return the name including the metadata arity suffix. /// </summary> public override string MetadataName { get { return MangleName ? MetadataHelpers.ComposeAritySuffixedMetadataName(Name, Arity) : Name; } } /// <summary> /// Should the name returned by Name property be mangled with [`arity] suffix in order to get metadata name. /// Must return False for a type with Arity == 0. /// </summary> internal abstract bool MangleName { // Intentionally no default implementation to force consideration of appropriate implementation for each new subclass get; } /// <summary> /// Collection of names of members declared within this type. May return duplicates. /// </summary> public abstract IEnumerable<string> MemberNames { get; } /// <summary> /// Get all the members of this symbol. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract override ImmutableArray<Symbol> GetMembers(); /// <summary> /// Get all the members of this symbol that have a particular name. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are /// no members with this name, returns an empty ImmutableArray. Never returns null.</returns> public abstract override ImmutableArray<Symbol> GetMembers(string name); /// <summary> /// A lightweight check for whether this type has a possible clone method. This is less costly than GetMembers, /// particularly for PE symbols, and can be used as a cheap heuristic for whether to fully search through all /// members of this type for a valid clone method. /// </summary> internal abstract bool HasPossibleWellKnownCloneMethod(); internal virtual ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name) { return GetMembers(name); } /// <summary> /// Get all the members of this symbol that are types. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract override ImmutableArray<NamedTypeSymbol> GetTypeMembers(); /// <summary> /// Get all the members of this symbol that are types that have a particular name, of any arity. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name. /// If this symbol has no type members with this name, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name); /// <summary> /// Get all the members of this symbol that are types that have a particular name and arity /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name and arity. /// If this symbol has no type members with this name and arity, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity); /// <summary> /// Get all instance field and event members. /// </summary> /// <remarks> /// For source symbols may be called while calculating /// <see cref="NamespaceOrTypeSymbol.GetMembersUnordered"/>. /// </remarks> internal virtual IEnumerable<Symbol> GetInstanceFieldsAndEvents() { return GetMembersUnordered().Where(IsInstanceFieldOrEvent); } protected static Func<Symbol, bool> IsInstanceFieldOrEvent = symbol => { if (!symbol.IsStatic) { switch (symbol.Kind) { case SymbolKind.Field: case SymbolKind.Event: return true; } } return false; }; /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns NotApplicable. /// </summary> public abstract override Accessibility DeclaredAccessibility { get; } /// <summary> /// Used to implement visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitNamedType(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitNamedType(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitNamedType(this); } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol. /// </summary> /// <remarks> /// Never returns null (empty instead). /// Expected implementations: for source, return type and field members; for metadata, return all members. /// </remarks> internal abstract ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(); /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol that have a particular name. /// </summary> /// <remarks> /// Never returns null (empty instead). /// Expected implementations: for source, return type and field members; for metadata, return all members. /// </remarks> internal abstract ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name); /// <summary> /// Gets the kind of this symbol. /// </summary> public override SymbolKind Kind // Cannot seal this method because of the ErrorSymbol. { get { return SymbolKind.NamedType; } } internal abstract NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved); internal abstract ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved); public override int GetHashCode() { // return a distinguished value for 'object' so we can return the same value for 'dynamic'. // That's because the hash code ignores the distinction between dynamic and object. It also // ignores custom modifiers. if (this.SpecialType == SpecialType.System_Object) { return (int)SpecialType.System_Object; } // OriginalDefinition must be object-equivalent. return RuntimeHelpers.GetHashCode(OriginalDefinition); } /// <summary> /// Compares this type to another type. /// </summary> internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if ((object)t2 == this) return true; if ((object)t2 == null) return false; if ((comparison & TypeCompareKind.IgnoreDynamic) != 0) { if (t2.TypeKind == TypeKind.Dynamic) { // if ignoring dynamic, then treat dynamic the same as the type 'object' if (this.SpecialType == SpecialType.System_Object) { return true; } } } NamedTypeSymbol other = t2 as NamedTypeSymbol; if ((object)other == null) return false; // Compare OriginalDefinitions. var thisOriginalDefinition = this.OriginalDefinition; var otherOriginalDefinition = other.OriginalDefinition; bool thisIsOriginalDefinition = ((object)this == (object)thisOriginalDefinition); bool otherIsOriginalDefinition = ((object)other == (object)otherOriginalDefinition); if (thisIsOriginalDefinition && otherIsOriginalDefinition) { // If we continue, we either return false, or get into a cycle. return false; } if ((thisIsOriginalDefinition || otherIsOriginalDefinition) && (comparison & (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) == 0) { return false; } // CONSIDER: original definitions are not unique for missing metadata type // symbols. Therefore this code may not behave correctly if 'this' is List<int> // where List`1 is a missing metadata type symbol, and other is similarly List<int> // but for a reference-distinct List`1. if (!Equals(thisOriginalDefinition, otherOriginalDefinition, comparison)) { return false; } // The checks above are supposed to handle the vast majority of cases. // More complicated cases are handled in a special helper to make the common case scenario simple/fast (fewer locals and smaller stack frame) return EqualsComplicatedCases(other, comparison); } /// <summary> /// Helper for more complicated cases of Equals like when we have generic instantiations or types nested within them. /// </summary> private bool EqualsComplicatedCases(NamedTypeSymbol other, TypeCompareKind comparison) { if ((object)this.ContainingType != null && !this.ContainingType.Equals(other.ContainingType, comparison)) { return false; } var thisIsNotConstructed = ReferenceEquals(ConstructedFrom, this); var otherIsNotConstructed = ReferenceEquals(other.ConstructedFrom, other); if (thisIsNotConstructed && otherIsNotConstructed) { // Note that the arguments might appear different here due to alpha-renaming. For example, given // class A<T> { class B<U> {} } // The type A<int>.B<int> is "constructed from" A<int>.B<1>, which may be a distinct type object // with a different alpha-renaming of B's type parameter every time that type expression is bound, // but these should be considered the same type each time. return true; } if (this.IsUnboundGenericType != other.IsUnboundGenericType) { return false; } if ((thisIsNotConstructed || otherIsNotConstructed) && (comparison & (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) == 0) { return false; } var typeArguments = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var otherTypeArguments = other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; int count = typeArguments.Length; // since both are constructed from the same (original) type, they must have the same arity Debug.Assert(count == otherTypeArguments.Length); for (int i = 0; i < count; i++) { var typeArgument = typeArguments[i]; var otherTypeArgument = otherTypeArguments[i]; if (!typeArgument.Equals(otherTypeArgument, comparison)) { return false; } } if (this.IsTupleType && !tupleNamesEquals(other, comparison)) { return false; } return true; bool tupleNamesEquals(NamedTypeSymbol other, TypeCompareKind comparison) { // Make sure field names are the same. if ((comparison & TypeCompareKind.IgnoreTupleNames) == 0) { var elementNames = TupleElementNames; var otherElementNames = other.TupleElementNames; return elementNames.IsDefault ? otherElementNames.IsDefault : !otherElementNames.IsDefault && elementNames.SequenceEqual(otherElementNames); } return true; } } internal override void AddNullableTransforms(ArrayBuilder<byte> transforms) { ContainingType?.AddNullableTransforms(transforms); foreach (TypeWithAnnotations arg in this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { arg.AddNullableTransforms(transforms); } } internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result) { if (!IsGenericType) { result = this; return true; } var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllTypeArgumentsNoUseSiteDiagnostics(allTypeArguments); bool haveChanges = false; for (int i = 0; i < allTypeArguments.Count; i++) { TypeWithAnnotations oldTypeArgument = allTypeArguments[i]; TypeWithAnnotations newTypeArgument; if (!oldTypeArgument.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out newTypeArgument)) { allTypeArguments.Free(); result = this; return false; } else if (!oldTypeArgument.IsSameAs(newTypeArgument)) { allTypeArguments[i] = newTypeArgument; haveChanges = true; } } result = haveChanges ? this.WithTypeArguments(allTypeArguments.ToImmutable()) : this; allTypeArguments.Free(); return true; } internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform) { if (!IsGenericType) { return this; } var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllTypeArgumentsNoUseSiteDiagnostics(allTypeArguments); bool haveChanges = false; for (int i = 0; i < allTypeArguments.Count; i++) { TypeWithAnnotations oldTypeArgument = allTypeArguments[i]; TypeWithAnnotations newTypeArgument = transform(oldTypeArgument); if (!oldTypeArgument.IsSameAs(newTypeArgument)) { allTypeArguments[i] = newTypeArgument; haveChanges = true; } } NamedTypeSymbol result = haveChanges ? this.WithTypeArguments(allTypeArguments.ToImmutable()) : this; allTypeArguments.Free(); return result; } internal NamedTypeSymbol WithTypeArguments(ImmutableArray<TypeWithAnnotations> allTypeArguments) { var definition = this.OriginalDefinition; TypeMap substitution = new TypeMap(definition.GetAllTypeParameters(), allTypeArguments); return substitution.SubstituteNamedType(definition).WithTupleDataFrom(this); } internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) { Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); if (!IsGenericType) { return other.IsDynamic() ? other : this; } var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); bool haveChanges = MergeEquivalentTypeArguments(this, (NamedTypeSymbol)other, variance, allTypeParameters, allTypeArguments); NamedTypeSymbol result; if (haveChanges) { TypeMap substitution = new TypeMap(allTypeParameters.ToImmutable(), allTypeArguments.ToImmutable()); result = substitution.SubstituteNamedType(this.OriginalDefinition); } else { result = this; } allTypeArguments.Free(); allTypeParameters.Free(); return IsTupleType ? MergeTupleNames((NamedTypeSymbol)other, result) : result; } /// <summary> /// Merges nullability of all type arguments from the `typeA` and `typeB`. /// The type parameters are added to `allTypeParameters`; the merged /// type arguments are added to `allTypeArguments`; and the method /// returns true if there were changes from the original `typeA`. /// </summary> private static bool MergeEquivalentTypeArguments( NamedTypeSymbol typeA, NamedTypeSymbol typeB, VarianceKind variance, ArrayBuilder<TypeParameterSymbol> allTypeParameters, ArrayBuilder<TypeWithAnnotations> allTypeArguments) { Debug.Assert(typeA.IsGenericType); Debug.Assert(typeA.Equals(typeB, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // Tuple types act as covariant when merging equivalent types. bool isTuple = typeA.IsTupleType; var definition = typeA.OriginalDefinition; bool haveChanges = false; while (true) { var typeParameters = definition.TypeParameters; if (typeParameters.Length > 0) { var typeArgumentsA = typeA.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var typeArgumentsB = typeB.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; allTypeParameters.AddRange(typeParameters); for (int i = 0; i < typeArgumentsA.Length; i++) { TypeWithAnnotations typeArgumentA = typeArgumentsA[i]; TypeWithAnnotations typeArgumentB = typeArgumentsB[i]; VarianceKind typeArgumentVariance = GetTypeArgumentVariance(variance, isTuple ? VarianceKind.Out : typeParameters[i].Variance); TypeWithAnnotations merged = typeArgumentA.MergeEquivalentTypes(typeArgumentB, typeArgumentVariance); allTypeArguments.Add(merged); if (!typeArgumentA.IsSameAs(merged)) { haveChanges = true; } } } definition = definition.ContainingType; if (definition is null) { break; } typeA = typeA.ContainingType; typeB = typeB.ContainingType; variance = VarianceKind.None; } return haveChanges; } private static VarianceKind GetTypeArgumentVariance(VarianceKind typeVariance, VarianceKind typeParameterVariance) { switch (typeVariance) { case VarianceKind.In: switch (typeParameterVariance) { case VarianceKind.In: return VarianceKind.Out; case VarianceKind.Out: return VarianceKind.In; default: return VarianceKind.None; } case VarianceKind.Out: return typeParameterVariance; default: return VarianceKind.None; } } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments">The immediate type arguments to be replaced for type /// parameters in the type.</param> public NamedTypeSymbol Construct(params TypeSymbol[] typeArguments) { // https://github.com/dotnet/roslyn/issues/30064: We should fix the callers to pass TypeWithAnnotations[] instead of TypeSymbol[]. return ConstructWithoutModifiers(typeArguments.AsImmutableOrNull(), false); } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments">The immediate type arguments to be replaced for type /// parameters in the type.</param> public NamedTypeSymbol Construct(ImmutableArray<TypeSymbol> typeArguments) { // https://github.com/dotnet/roslyn/issues/30064: We should fix the callers to pass ImmutableArray<TypeWithAnnotations> instead of ImmutableArray<TypeSymbol>. return ConstructWithoutModifiers(typeArguments, false); } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments"></param> public NamedTypeSymbol Construct(IEnumerable<TypeSymbol> typeArguments) { // https://github.com/dotnet/roslyn/issues/30064: We should fix the callers to pass IEnumerable<TypeWithAnnotations> instead of IEnumerable<TypeSymbol>. return ConstructWithoutModifiers(typeArguments.AsImmutableOrNull(), false); } /// <summary> /// Returns an unbound generic type of this named type. /// </summary> public NamedTypeSymbol ConstructUnboundGenericType() { return OriginalDefinition.AsUnboundGenericType(); } internal NamedTypeSymbol GetUnboundGenericTypeOrSelf() { if (!this.IsGenericType) { return this; } return this.ConstructUnboundGenericType(); } /// <summary> /// Gets a value indicating whether this type has an EmbeddedAttribute or not. /// </summary> internal abstract bool HasCodeAnalysisEmbeddedAttribute { get; } /// <summary> /// Gets a value indicating whether this type has System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute or not. /// </summary> internal abstract bool IsInterpolatedStringHandlerType { get; } internal static readonly Func<TypeWithAnnotations, bool> TypeWithAnnotationsIsNullFunction = type => !type.HasType; internal static readonly Func<TypeWithAnnotations, bool> TypeWithAnnotationsIsErrorType = type => type.HasType && type.Type.IsErrorType(); private NamedTypeSymbol ConstructWithoutModifiers(ImmutableArray<TypeSymbol> typeArguments, bool unbound) { ImmutableArray<TypeWithAnnotations> modifiedArguments; if (typeArguments.IsDefault) { modifiedArguments = default(ImmutableArray<TypeWithAnnotations>); } else { modifiedArguments = typeArguments.SelectAsArray(t => TypeWithAnnotations.Create(t)); } return Construct(modifiedArguments, unbound); } internal NamedTypeSymbol Construct(ImmutableArray<TypeWithAnnotations> typeArguments) { return Construct(typeArguments, unbound: false); } internal NamedTypeSymbol Construct(ImmutableArray<TypeWithAnnotations> typeArguments, bool unbound) { if (!ReferenceEquals(this, ConstructedFrom)) { throw new InvalidOperationException(CSharpResources.CannotCreateConstructedFromConstructed); } if (this.Arity == 0) { throw new InvalidOperationException(CSharpResources.CannotCreateConstructedFromNongeneric); } if (typeArguments.IsDefault) { throw new ArgumentNullException(nameof(typeArguments)); } if (typeArguments.Any(TypeWithAnnotationsIsNullFunction)) { throw new ArgumentException(CSharpResources.TypeArgumentCannotBeNull, nameof(typeArguments)); } if (typeArguments.Length != this.Arity) { throw new ArgumentException(CSharpResources.WrongNumberOfTypeArguments, nameof(typeArguments)); } Debug.Assert(!unbound || typeArguments.All(TypeWithAnnotationsIsErrorType)); if (ConstructedNamedTypeSymbol.TypeParametersMatchTypeArguments(this.TypeParameters, typeArguments)) { return this; } return this.ConstructCore(typeArguments, unbound); } protected virtual NamedTypeSymbol ConstructCore(ImmutableArray<TypeWithAnnotations> typeArguments, bool unbound) { return new ConstructedNamedTypeSymbol(this, typeArguments, unbound); } /// <summary> /// True if this type or some containing type has type parameters. /// </summary> public bool IsGenericType { get { for (var current = this; !ReferenceEquals(current, null); current = current.ContainingType) { if (current.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length != 0) { return true; } } return false; } } /// <summary> /// True if this is a reference to an <em>unbound</em> generic type. These occur only /// within a <c>typeof</c> expression. A generic type is considered <em>unbound</em> /// if all of the type argument lists in its fully qualified name are empty. /// Note that the type arguments of an unbound generic type will be returned as error /// types because they do not really have type arguments. An unbound generic type /// yields null for its BaseType and an empty result for its Interfaces. /// </summary> public virtual bool IsUnboundGenericType { get { return false; } } // Given C<int>.D<string, double>, yields { int, string, double } internal void GetAllTypeArguments(ArrayBuilder<TypeSymbol> builder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var outer = ContainingType; if (!ReferenceEquals(outer, null)) { outer.GetAllTypeArguments(builder, ref useSiteInfo); } foreach (var argument in TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { builder.Add(argument.Type); } } internal ImmutableArray<TypeWithAnnotations> GetAllTypeArguments(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayBuilder<TypeWithAnnotations> builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllTypeArguments(builder, ref useSiteInfo); return builder.ToImmutableAndFree(); } internal void GetAllTypeArguments(ArrayBuilder<TypeWithAnnotations> builder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var outer = ContainingType; if (!ReferenceEquals(outer, null)) { outer.GetAllTypeArguments(builder, ref useSiteInfo); } builder.AddRange(TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); } internal void GetAllTypeArgumentsNoUseSiteDiagnostics(ArrayBuilder<TypeWithAnnotations> builder) { ContainingType?.GetAllTypeArgumentsNoUseSiteDiagnostics(builder); builder.AddRange(TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); } internal int AllTypeArgumentCount() { int count = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; var outer = ContainingType; if (!ReferenceEquals(outer, null)) { count += outer.AllTypeArgumentCount(); } return count; } internal ImmutableArray<TypeWithAnnotations> GetTypeParametersAsTypeArguments() { return TypeMap.TypeParametersAsTypeSymbolsWithAnnotations(this.TypeParameters); } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new virtual NamedTypeSymbol OriginalDefinition { get { return this; } } protected sealed override TypeSymbol OriginalTypeSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// Returns the map from type parameters to type arguments. /// If this is not a generic type instantiation, returns null. /// The map targets the original definition of the type. /// </summary> internal virtual TypeMap TypeSubstitution { get { return null; } } internal virtual NamedTypeSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(this.IsDefinition); Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol.OriginalDefinition)); return newOwner.IsDefinition ? this : new SubstitutedNestedTypeSymbol((SubstitutedNamedTypeSymbol)newOwner, this); } #region Use-Site Diagnostics internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { UseSiteInfo<AssemblySymbol> result = new UseSiteInfo<AssemblySymbol>(PrimaryDependency); if (this.IsDefinition) { return result; } // Check definition, type arguments if (!DeriveUseSiteInfoFromType(ref result, this.OriginalDefinition)) { DeriveUseSiteDiagnosticFromTypeArguments(ref result); } return result; } private bool DeriveUseSiteDiagnosticFromTypeArguments(ref UseSiteInfo<AssemblySymbol> result) { NamedTypeSymbol currentType = this; do { foreach (TypeWithAnnotations arg in currentType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { if (DeriveUseSiteInfoFromType(ref result, arg, AllowedRequiredModifierType.None)) { return true; } } currentType = currentType.ContainingType; } while (currentType?.IsDefinition == false); return false; } internal DiagnosticInfo CalculateUseSiteDiagnostic() { DiagnosticInfo result = null; // Check base type. if (MergeUseSiteDiagnostics(ref result, DeriveUseSiteDiagnosticFromBase())) { return result; } // If we reach a type (Me) that is in an assembly with unified references, // we check if that type definition depends on a type from a unified reference. if (this.ContainingModule.HasUnifiedReferences) { HashSet<TypeSymbol> unificationCheckedTypes = null; if (GetUnificationUseSiteDiagnosticRecursive(ref result, this, ref unificationCheckedTypes)) { return result; } } return result; } private DiagnosticInfo DeriveUseSiteDiagnosticFromBase() { NamedTypeSymbol @base = this.BaseTypeNoUseSiteDiagnostics; while ((object)@base != null) { if (@base.IsErrorType() && @base is NoPiaIllegalGenericInstantiationSymbol) { return @base.GetUseSiteInfo().DiagnosticInfo; } @base = @base.BaseTypeNoUseSiteDiagnostics; } return null; } internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { if (!this.MarkCheckedIfNecessary(ref checkedTypes)) { return false; } Debug.Assert(owner.ContainingModule.HasUnifiedReferences); if (owner.ContainingModule.GetUnificationUseSiteDiagnostic(ref result, this)) { return true; } // We recurse into base types, interfaces and type *parameters* to check for // problems with constraints. We recurse into type *arguments* in the overload // in ConstructedNamedTypeSymbol. // // When we are binding a name with a nested type, Goo.Bar, then we ask for // use-site errors to be reported on both Goo and Goo.Bar. Therefore we should // not recurse into the containing type here; doing so will result in errors // being reported twice if Goo is bad. var @base = this.BaseTypeNoUseSiteDiagnostics; if ((object)@base != null && @base.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } return GetUnificationUseSiteDiagnosticRecursive(ref result, this.InterfacesNoUseSiteDiagnostics(), owner, ref checkedTypes) || GetUnificationUseSiteDiagnosticRecursive(ref result, this.TypeParameters, owner, ref checkedTypes); } #endregion /// <summary> /// True if the type itself is excluded from code coverage instrumentation. /// True for source types marked with <see cref="AttributeDescription.ExcludeFromCodeCoverageAttribute"/>. /// </summary> internal virtual bool IsDirectlyExcludedFromCodeCoverage { get => false; } /// <summary> /// True if this symbol has a special name (metadata flag SpecialName is set). /// </summary> internal abstract bool HasSpecialName { get; } /// <summary> /// Returns a flag indicating whether this symbol is ComImport. /// </summary> /// <remarks> /// A type can me marked as a ComImport type in source by applying the <see cref="System.Runtime.InteropServices.ComImportAttribute"/> /// </remarks> internal abstract bool IsComImport { get; } /// <summary> /// True if the type is a Windows runtime type. /// </summary> /// <remarks> /// A type can me marked as a Windows runtime type in source by applying the WindowsRuntimeImportAttribute. /// WindowsRuntimeImportAttribute is a pseudo custom attribute defined as an internal class in System.Runtime.InteropServices.WindowsRuntime namespace. /// This is needed to mark Windows runtime types which are redefined in mscorlib.dll and System.Runtime.WindowsRuntime.dll. /// These two assemblies are special as they implement the CLR's support for WinRT. /// </remarks> internal abstract bool IsWindowsRuntimeImport { get; } /// <summary> /// True if the type should have its WinRT interfaces projected onto .NET types and /// have missing .NET interface members added to the type. /// </summary> internal abstract bool ShouldAddWinRTMembers { get; } /// <summary> /// Returns a flag indicating whether this symbol has at least one applied/inherited conditional attribute. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal bool IsConditional { get { if (this.GetAppliedConditionalSymbols().Any()) { return true; } // Conditional attributes are inherited by derived types. var baseType = this.BaseTypeNoUseSiteDiagnostics; return (object)baseType != null ? baseType.IsConditional : false; } } /// <summary> /// True if the type is serializable (has Serializable metadata flag). /// </summary> public abstract bool IsSerializable { get; } /// <summary> /// Returns true if locals are to be initialized /// </summary> public abstract bool AreLocalsZeroed { get; } /// <summary> /// Type layout information (ClassLayout metadata and layout kind flags). /// </summary> internal abstract TypeLayout Layout { get; } /// <summary> /// The default charset used for type marshalling. /// Can be changed via <see cref="DefaultCharSetAttribute"/> applied on the containing module. /// </summary> protected CharSet DefaultMarshallingCharSet { get { return this.GetEffectiveDefaultMarshallingCharSet() ?? CharSet.Ansi; } } /// <summary> /// Marshalling charset of string data fields within the type (string formatting flags in metadata). /// </summary> internal abstract CharSet MarshallingCharSet { get; } /// <summary> /// True if the type has declarative security information (HasSecurity flags). /// </summary> internal abstract bool HasDeclarativeSecurity { get; } /// <summary> /// Declaration security information associated with this type, or null if there is none. /// </summary> internal abstract IEnumerable<Cci.SecurityAttribute> GetSecurityInformation(); /// <summary> /// Returns a sequence of preprocessor symbols specified in <see cref="ConditionalAttribute"/> applied on this symbol, or null if there are none. /// </summary> internal abstract ImmutableArray<string> GetAppliedConditionalSymbols(); /// <summary> /// If <see cref="CoClassAttribute"/> was applied to the type and the attribute argument is a valid named type argument, i.e. accessible class type, then it returns the type symbol for the argument. /// Otherwise, returns null. /// </summary> /// <remarks> /// <para> /// This property invokes force completion of attributes. If you are accessing this property /// from the binder, make sure that we are not binding within an Attribute context. /// This could lead to a possible cycle in attribute binding. /// We can avoid this cycle by first checking if we are within the context of an Attribute argument, /// i.e. if(!binder.InAttributeArgument) { ... namedType.ComImportCoClass ... } /// </para> /// <para> /// CONSIDER: We can remove the above restriction and possibility of cycle if we do an /// early binding of some well known attributes. /// </para> /// </remarks> internal virtual NamedTypeSymbol ComImportCoClass { get { return null; } } /// <summary> /// If class represents fixed buffer, this property returns the FixedElementField /// </summary> internal virtual FieldSymbol FixedElementField { get { return null; } } /// <summary> /// Requires less computation than <see cref="TypeSymbol.TypeKind"/> == <see cref="TypeKind.Interface"/>. /// </summary> /// <remarks> /// Metadata types need to compute their base types in order to know their TypeKinds, and that can lead /// to cycles if base types are already being computed. /// </remarks> /// <returns>True if this is an interface type.</returns> internal abstract bool IsInterface { get; } /// <summary> /// Verify if the given type can be used to back a tuple type /// and return cardinality of that tuple type in <paramref name="tupleCardinality"/>. /// </summary> /// <param name="tupleCardinality">If method returns true, contains cardinality of the compatible tuple type.</param> /// <returns></returns> internal bool IsTupleTypeOfCardinality(out int tupleCardinality) { // Should this be optimized for perf (caching for VT<0> to VT<7>, etc.)? if (!IsUnboundGenericType && ContainingSymbol?.Kind == SymbolKind.Namespace && ContainingNamespace.ContainingNamespace?.IsGlobalNamespace == true && Name == ValueTupleTypeName && ContainingNamespace.Name == MetadataHelpers.SystemString) { int arity = Arity; if (arity >= 0 && arity < ValueTupleRestPosition) { tupleCardinality = arity; return true; } else if (arity == ValueTupleRestPosition && !IsDefinition) { // Skip through "Rest" extensions TypeSymbol typeToCheck = this; int levelsOfNesting = 0; do { levelsOfNesting++; typeToCheck = ((NamedTypeSymbol)typeToCheck).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[ValueTupleRestPosition - 1].Type; } while (Equals(typeToCheck.OriginalDefinition, this.OriginalDefinition, TypeCompareKind.ConsiderEverything) && !typeToCheck.IsDefinition); arity = (typeToCheck as NamedTypeSymbol)?.Arity ?? 0; if (arity > 0 && arity < ValueTupleRestPosition && ((NamedTypeSymbol)typeToCheck).IsTupleTypeOfCardinality(out tupleCardinality)) { Debug.Assert(tupleCardinality < ValueTupleRestPosition); tupleCardinality += (ValueTupleRestPosition - 1) * levelsOfNesting; return true; } } } tupleCardinality = 0; return false; } /// <summary> /// Returns an instance of a symbol that represents a native integer /// if this underlying symbol represents System.IntPtr or System.UIntPtr. /// For other symbols, throws <see cref="System.InvalidOperationException"/>. /// </summary> internal abstract NamedTypeSymbol AsNativeInteger(); /// <summary> /// If this is a native integer, returns the symbol for the underlying type, /// either <see cref="System.IntPtr"/> or <see cref="System.UIntPtr"/>. /// Otherwise, returns null. /// </summary> internal abstract NamedTypeSymbol NativeIntegerUnderlyingType { get; } /// <summary> /// Returns true if the type is defined in source and contains field initializers. /// This method is only valid on a definition. /// </summary> internal virtual bool HasFieldInitializers() { Debug.Assert(IsDefinition); return false; } protected override ISymbol CreateISymbol() { return new PublicModel.NonErrorNamedTypeSymbol(this, DefaultNullableAnnotation); } protected override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { Debug.Assert(nullableAnnotation != DefaultNullableAnnotation); return new PublicModel.NonErrorNamedTypeSymbol(this, nullableAnnotation); } INamedTypeSymbolInternal INamedTypeSymbolInternal.EnumUnderlyingType { get { return this.EnumUnderlyingType; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a type other than an array, a pointer, a type parameter, and dynamic. /// </summary> internal abstract partial class NamedTypeSymbol : TypeSymbol, INamedTypeSymbolInternal { private bool _hasNoBaseCycles; // Only the compiler can create NamedTypeSymbols. internal NamedTypeSymbol(TupleExtraData tupleData = null) { _lazyTupleData = tupleData; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO: How should anonymous types be represented? One possible options: have an // IsAnonymous on this type. The Name would then return a unique compiler-generated // type that matches the metadata name. /// <summary> /// Returns the arity of this type, or the number of type parameters it takes. /// A non-generic type has zero arity. /// </summary> public abstract int Arity { get; } /// <summary> /// Returns the type parameters that this type has. If this is a non-generic type, /// returns an empty ImmutableArray. /// </summary> public abstract ImmutableArray<TypeParameterSymbol> TypeParameters { get; } /// <summary> /// Returns the type arguments that have been substituted for the type parameters. /// If nothing has been substituted for a give type parameters, /// then the type parameter itself is consider the type argument. /// </summary> internal abstract ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get; } internal ImmutableArray<TypeWithAnnotations> TypeArgumentsWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; foreach (var typeArgument in result) { typeArgument.Type.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } internal TypeWithAnnotations TypeArgumentWithDefinitionUseSiteDiagnostics(int index, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[index]; result.Type.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); return result; } /// <summary> /// Returns the type symbol that this type was constructed from. This type symbol /// has the same containing type (if any), but has type arguments that are the same /// as the type parameters (although its containing type might not). /// </summary> public abstract NamedTypeSymbol ConstructedFrom { get; } /// <summary> /// For enum types, gets the underlying type. Returns null on all other /// kinds of types. /// </summary> public virtual NamedTypeSymbol EnumUnderlyingType { get { return null; } } public override NamedTypeSymbol ContainingType { get { // we can do this since if a type does not live directly in a type // there is no containing type at all // NOTE: many derived types will override this with even better implementation // since most know their containing types/symbols directly return this.ContainingSymbol as NamedTypeSymbol; } } /// <summary> /// Returns true for a struct type containing a cycle. /// This property is intended for flow analysis only /// since it is only implemented for source types. /// </summary> internal virtual bool KnownCircularStruct { get { return false; } } internal bool KnownToHaveNoDeclaredBaseCycles { get { return _hasNoBaseCycles; } } internal void SetKnownToHaveNoDeclaredBaseCycles() { _hasNoBaseCycles = true; } /// <summary> /// Is this a NoPia local type explicitly declared in source, i.e. /// top level type with a TypeIdentifier attribute on it? /// </summary> internal virtual bool IsExplicitDefinitionOfNoPiaLocalType { get { return false; } } /// <summary> /// Returns true and a string from the first GuidAttribute on the type, /// the string might be null or an invalid guid representation. False, /// if there is no GuidAttribute with string argument. /// </summary> internal virtual bool GetGuidString(out string guidString) { return GetGuidStringDefaultImplementation(out guidString); } #nullable enable /// <summary> /// For delegate types, gets the delegate's invoke method. Returns null on /// all other kinds of types. Note that it is possible to have an ill-formed /// delegate type imported from metadata which does not have an Invoke method. /// Such a type will be classified as a delegate but its DelegateInvokeMethod /// would be null. /// </summary> public MethodSymbol? DelegateInvokeMethod { get { if (TypeKind != TypeKind.Delegate) { return null; } var methods = GetMembers(WellKnownMemberNames.DelegateInvokeName); if (methods.Length != 1) { return null; } var method = methods[0] as MethodSymbol; //EDMAURER we used to also check 'method.IsVirtual' because section 13.6 //of the CLI spec dictates that it be virtual, but real world //working metadata has been found that contains an Invoke method that is //marked as virtual but not newslot (both of those must be combined to //meet the C# definition of virtual). Rather than weaken the check //I've removed it, as the Dev10 compiler makes no check, and we don't //stand to gain anything by having it. //return method != null && method.IsVirtual ? method : null; return method; } } #nullable disable /// <summary> /// Get the operators for this type by their metadata name /// </summary> internal ImmutableArray<MethodSymbol> GetOperators(string name) { ImmutableArray<Symbol> candidates = GetSimpleNonTypeMembers(name); if (candidates.IsEmpty) { return ImmutableArray<MethodSymbol>.Empty; } ArrayBuilder<MethodSymbol> operators = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (MethodSymbol candidate in candidates.OfType<MethodSymbol>()) { if (candidate.MethodKind == MethodKind.UserDefinedOperator || candidate.MethodKind == MethodKind.Conversion) { operators.Add(candidate); } } return operators.ToImmutableAndFree(); } /// <summary> /// Get the instance constructors for this type. /// </summary> public ImmutableArray<MethodSymbol> InstanceConstructors { get { return GetConstructors(includeInstance: true, includeStatic: false); } } /// <summary> /// Get the static constructors for this type. /// </summary> public ImmutableArray<MethodSymbol> StaticConstructors { get { return GetConstructors(includeInstance: false, includeStatic: true); } } /// <summary> /// Get the instance and static constructors for this type. /// </summary> public ImmutableArray<MethodSymbol> Constructors { get { return GetConstructors(includeInstance: true, includeStatic: true); } } private ImmutableArray<MethodSymbol> GetConstructors(bool includeInstance, bool includeStatic) { Debug.Assert(includeInstance || includeStatic); ImmutableArray<Symbol> instanceCandidates = includeInstance ? GetMembers(WellKnownMemberNames.InstanceConstructorName) : ImmutableArray<Symbol>.Empty; ImmutableArray<Symbol> staticCandidates = includeStatic ? GetMembers(WellKnownMemberNames.StaticConstructorName) : ImmutableArray<Symbol>.Empty; if (instanceCandidates.IsEmpty && staticCandidates.IsEmpty) { return ImmutableArray<MethodSymbol>.Empty; } ArrayBuilder<MethodSymbol> constructors = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (Symbol candidate in instanceCandidates) { if (candidate is MethodSymbol method) { Debug.Assert(method.MethodKind == MethodKind.Constructor); constructors.Add(method); } } foreach (Symbol candidate in staticCandidates) { if (candidate is MethodSymbol method) { Debug.Assert(method.MethodKind == MethodKind.StaticConstructor); constructors.Add(method); } } return constructors.ToImmutableAndFree(); } /// <summary> /// Get the indexers for this type. /// </summary> /// <remarks> /// Won't include indexers that are explicit interface implementations. /// </remarks> public ImmutableArray<PropertySymbol> Indexers { get { ImmutableArray<Symbol> candidates = GetSimpleNonTypeMembers(WellKnownMemberNames.Indexer); if (candidates.IsEmpty) { return ImmutableArray<PropertySymbol>.Empty; } // The common case will be returning a list with the same elements as "candidates", // but we need a list of PropertySymbols, so we're stuck building a new list anyway. ArrayBuilder<PropertySymbol> indexers = ArrayBuilder<PropertySymbol>.GetInstance(); foreach (Symbol candidate in candidates) { if (candidate.Kind == SymbolKind.Property) { Debug.Assert(((PropertySymbol)candidate).IsIndexer); indexers.Add((PropertySymbol)candidate); } } return indexers.ToImmutableAndFree(); } } /// <summary> /// Returns true if this type might contain extension methods. If this property /// returns false, there are no extension methods in this type. /// </summary> /// <remarks> /// This property allows the search for extension methods to be narrowed quickly. /// </remarks> public abstract bool MightContainExtensionMethods { get; } internal void GetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { if (this.MightContainExtensionMethods) { DoGetExtensionMethods(methods, nameOpt, arity, options); } } internal void DoGetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { var members = nameOpt == null ? this.GetMembersUnordered() : this.GetSimpleNonTypeMembers(nameOpt); foreach (var member in members) { if (member.Kind == SymbolKind.Method) { var method = (MethodSymbol)member; if (method.IsExtensionMethod && ((options & LookupOptions.AllMethodsOnArityZero) != 0 || arity == method.Arity)) { var thisParam = method.Parameters.First(); if ((thisParam.RefKind == RefKind.Ref && !thisParam.Type.IsValueType) || (thisParam.RefKind == RefKind.In && thisParam.Type.TypeKind != TypeKind.Struct)) { // For ref and ref-readonly extension methods, receivers need to be of the correct types to be considered in lookup continue; } Debug.Assert(method.MethodKind != MethodKind.ReducedExtension); methods.Add(method); } } } } // TODO: Probably should provide similar accessors for static constructor, destructor, // TODO: operators, conversions. /// <summary> /// Returns true if this type is known to be a reference type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public override bool IsReferenceType { get { var kind = TypeKind; return kind != TypeKind.Enum && kind != TypeKind.Struct && kind != TypeKind.Error; } } /// <summary> /// Returns true if this type is known to be a value type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public override bool IsValueType { get { var kind = TypeKind; return kind == TypeKind.Struct || kind == TypeKind.Enum; } } internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // CONSIDER: we could cache this, but it's only expensive for non-special struct types // that are pointed to. For now, only cache on SourceMemberContainerSymbol since it fits // nicely into the flags variable. return BaseTypeAnalysis.GetManagedKind(this, ref useSiteInfo); } /// <summary> /// Gets the associated attribute usage info for an attribute type. /// </summary> internal abstract AttributeUsageInfo GetAttributeUsageInfo(); /// <summary> /// Returns true if the type is a Script class. /// It might be an interactive submission class or a Script class in a csx file. /// </summary> public virtual bool IsScriptClass { get { return false; } } internal bool IsSubmissionClass { get { return TypeKind == TypeKind.Submission; } } internal SynthesizedInstanceConstructor GetScriptConstructor() { Debug.Assert(IsScriptClass); return (SynthesizedInstanceConstructor)InstanceConstructors.Single(); } internal SynthesizedInteractiveInitializerMethod GetScriptInitializer() { Debug.Assert(IsScriptClass); return (SynthesizedInteractiveInitializerMethod)GetMembers(SynthesizedInteractiveInitializerMethod.InitializerName).Single(); } internal SynthesizedEntryPointSymbol GetScriptEntryPoint() { Debug.Assert(IsScriptClass); var name = (TypeKind == TypeKind.Submission) ? SynthesizedEntryPointSymbol.FactoryName : SynthesizedEntryPointSymbol.MainName; return (SynthesizedEntryPointSymbol)GetMembers(name).Single(); } /// <summary> /// Returns true if the type is the implicit class that holds onto invalid global members (like methods or /// statements in a non script file). /// </summary> public virtual bool IsImplicitClass { get { return false; } } /// <summary> /// Gets the name of this symbol. Symbols without a name return the empty string; null is /// never returned. /// </summary> public abstract override string Name { get; } /// <summary> /// Return the name including the metadata arity suffix. /// </summary> public override string MetadataName { get { return MangleName ? MetadataHelpers.ComposeAritySuffixedMetadataName(Name, Arity) : Name; } } /// <summary> /// Should the name returned by Name property be mangled with [`arity] suffix in order to get metadata name. /// Must return False for a type with Arity == 0. /// </summary> internal abstract bool MangleName { // Intentionally no default implementation to force consideration of appropriate implementation for each new subclass get; } /// <summary> /// Collection of names of members declared within this type. May return duplicates. /// </summary> public abstract IEnumerable<string> MemberNames { get; } /// <summary> /// Get all the members of this symbol. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract override ImmutableArray<Symbol> GetMembers(); /// <summary> /// Get all the members of this symbol that have a particular name. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are /// no members with this name, returns an empty ImmutableArray. Never returns null.</returns> public abstract override ImmutableArray<Symbol> GetMembers(string name); /// <summary> /// A lightweight check for whether this type has a possible clone method. This is less costly than GetMembers, /// particularly for PE symbols, and can be used as a cheap heuristic for whether to fully search through all /// members of this type for a valid clone method. /// </summary> internal abstract bool HasPossibleWellKnownCloneMethod(); internal virtual ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name) { return GetMembers(name); } /// <summary> /// Get all the members of this symbol that are types. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract override ImmutableArray<NamedTypeSymbol> GetTypeMembers(); /// <summary> /// Get all the members of this symbol that are types that have a particular name, of any arity. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name. /// If this symbol has no type members with this name, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name); /// <summary> /// Get all the members of this symbol that are types that have a particular name and arity /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name and arity. /// If this symbol has no type members with this name and arity, /// returns an empty ImmutableArray. Never returns null.</returns> public abstract override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity); /// <summary> /// Get all instance field and event members. /// </summary> /// <remarks> /// For source symbols may be called while calculating /// <see cref="NamespaceOrTypeSymbol.GetMembersUnordered"/>. /// </remarks> internal virtual IEnumerable<Symbol> GetInstanceFieldsAndEvents() { return GetMembersUnordered().Where(IsInstanceFieldOrEvent); } protected static Func<Symbol, bool> IsInstanceFieldOrEvent = symbol => { if (!symbol.IsStatic) { switch (symbol.Kind) { case SymbolKind.Field: case SymbolKind.Event: return true; } } return false; }; /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns NotApplicable. /// </summary> public abstract override Accessibility DeclaredAccessibility { get; } /// <summary> /// Used to implement visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitNamedType(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitNamedType(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitNamedType(this); } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol. /// </summary> /// <remarks> /// Never returns null (empty instead). /// Expected implementations: for source, return type and field members; for metadata, return all members. /// </remarks> internal abstract ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(); /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol that have a particular name. /// </summary> /// <remarks> /// Never returns null (empty instead). /// Expected implementations: for source, return type and field members; for metadata, return all members. /// </remarks> internal abstract ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name); /// <summary> /// Gets the kind of this symbol. /// </summary> public override SymbolKind Kind // Cannot seal this method because of the ErrorSymbol. { get { return SymbolKind.NamedType; } } internal abstract NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved); internal abstract ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved); public override int GetHashCode() { // return a distinguished value for 'object' so we can return the same value for 'dynamic'. // That's because the hash code ignores the distinction between dynamic and object. It also // ignores custom modifiers. if (this.SpecialType == SpecialType.System_Object) { return (int)SpecialType.System_Object; } // OriginalDefinition must be object-equivalent. return RuntimeHelpers.GetHashCode(OriginalDefinition); } /// <summary> /// Compares this type to another type. /// </summary> internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if ((object)t2 == this) return true; if ((object)t2 == null) return false; if ((comparison & TypeCompareKind.IgnoreDynamic) != 0) { if (t2.TypeKind == TypeKind.Dynamic) { // if ignoring dynamic, then treat dynamic the same as the type 'object' if (this.SpecialType == SpecialType.System_Object) { return true; } } } NamedTypeSymbol other = t2 as NamedTypeSymbol; if ((object)other == null) return false; // Compare OriginalDefinitions. var thisOriginalDefinition = this.OriginalDefinition; var otherOriginalDefinition = other.OriginalDefinition; bool thisIsOriginalDefinition = ((object)this == (object)thisOriginalDefinition); bool otherIsOriginalDefinition = ((object)other == (object)otherOriginalDefinition); if (thisIsOriginalDefinition && otherIsOriginalDefinition) { // If we continue, we either return false, or get into a cycle. return false; } if ((thisIsOriginalDefinition || otherIsOriginalDefinition) && (comparison & (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) == 0) { return false; } // CONSIDER: original definitions are not unique for missing metadata type // symbols. Therefore this code may not behave correctly if 'this' is List<int> // where List`1 is a missing metadata type symbol, and other is similarly List<int> // but for a reference-distinct List`1. if (!Equals(thisOriginalDefinition, otherOriginalDefinition, comparison)) { return false; } // The checks above are supposed to handle the vast majority of cases. // More complicated cases are handled in a special helper to make the common case scenario simple/fast (fewer locals and smaller stack frame) return EqualsComplicatedCases(other, comparison); } /// <summary> /// Helper for more complicated cases of Equals like when we have generic instantiations or types nested within them. /// </summary> private bool EqualsComplicatedCases(NamedTypeSymbol other, TypeCompareKind comparison) { if ((object)this.ContainingType != null && !this.ContainingType.Equals(other.ContainingType, comparison)) { return false; } var thisIsNotConstructed = ReferenceEquals(ConstructedFrom, this); var otherIsNotConstructed = ReferenceEquals(other.ConstructedFrom, other); if (thisIsNotConstructed && otherIsNotConstructed) { // Note that the arguments might appear different here due to alpha-renaming. For example, given // class A<T> { class B<U> {} } // The type A<int>.B<int> is "constructed from" A<int>.B<1>, which may be a distinct type object // with a different alpha-renaming of B's type parameter every time that type expression is bound, // but these should be considered the same type each time. return true; } if (this.IsUnboundGenericType != other.IsUnboundGenericType) { return false; } if ((thisIsNotConstructed || otherIsNotConstructed) && (comparison & (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) == 0) { return false; } var typeArguments = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var otherTypeArguments = other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; int count = typeArguments.Length; // since both are constructed from the same (original) type, they must have the same arity Debug.Assert(count == otherTypeArguments.Length); for (int i = 0; i < count; i++) { var typeArgument = typeArguments[i]; var otherTypeArgument = otherTypeArguments[i]; if (!typeArgument.Equals(otherTypeArgument, comparison)) { return false; } } if (this.IsTupleType && !tupleNamesEquals(other, comparison)) { return false; } return true; bool tupleNamesEquals(NamedTypeSymbol other, TypeCompareKind comparison) { // Make sure field names are the same. if ((comparison & TypeCompareKind.IgnoreTupleNames) == 0) { var elementNames = TupleElementNames; var otherElementNames = other.TupleElementNames; return elementNames.IsDefault ? otherElementNames.IsDefault : !otherElementNames.IsDefault && elementNames.SequenceEqual(otherElementNames); } return true; } } internal override void AddNullableTransforms(ArrayBuilder<byte> transforms) { ContainingType?.AddNullableTransforms(transforms); foreach (TypeWithAnnotations arg in this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { arg.AddNullableTransforms(transforms); } } internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result) { if (!IsGenericType) { result = this; return true; } var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllTypeArgumentsNoUseSiteDiagnostics(allTypeArguments); bool haveChanges = false; for (int i = 0; i < allTypeArguments.Count; i++) { TypeWithAnnotations oldTypeArgument = allTypeArguments[i]; TypeWithAnnotations newTypeArgument; if (!oldTypeArgument.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out newTypeArgument)) { allTypeArguments.Free(); result = this; return false; } else if (!oldTypeArgument.IsSameAs(newTypeArgument)) { allTypeArguments[i] = newTypeArgument; haveChanges = true; } } result = haveChanges ? this.WithTypeArguments(allTypeArguments.ToImmutable()) : this; allTypeArguments.Free(); return true; } internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform) { if (!IsGenericType) { return this; } var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllTypeArgumentsNoUseSiteDiagnostics(allTypeArguments); bool haveChanges = false; for (int i = 0; i < allTypeArguments.Count; i++) { TypeWithAnnotations oldTypeArgument = allTypeArguments[i]; TypeWithAnnotations newTypeArgument = transform(oldTypeArgument); if (!oldTypeArgument.IsSameAs(newTypeArgument)) { allTypeArguments[i] = newTypeArgument; haveChanges = true; } } NamedTypeSymbol result = haveChanges ? this.WithTypeArguments(allTypeArguments.ToImmutable()) : this; allTypeArguments.Free(); return result; } internal NamedTypeSymbol WithTypeArguments(ImmutableArray<TypeWithAnnotations> allTypeArguments) { var definition = this.OriginalDefinition; TypeMap substitution = new TypeMap(definition.GetAllTypeParameters(), allTypeArguments); return substitution.SubstituteNamedType(definition).WithTupleDataFrom(this); } internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) { Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); if (!IsGenericType) { return other.IsDynamic() ? other : this; } var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); bool haveChanges = MergeEquivalentTypeArguments(this, (NamedTypeSymbol)other, variance, allTypeParameters, allTypeArguments); NamedTypeSymbol result; if (haveChanges) { TypeMap substitution = new TypeMap(allTypeParameters.ToImmutable(), allTypeArguments.ToImmutable()); result = substitution.SubstituteNamedType(this.OriginalDefinition); } else { result = this; } allTypeArguments.Free(); allTypeParameters.Free(); return IsTupleType ? MergeTupleNames((NamedTypeSymbol)other, result) : result; } /// <summary> /// Merges nullability of all type arguments from the `typeA` and `typeB`. /// The type parameters are added to `allTypeParameters`; the merged /// type arguments are added to `allTypeArguments`; and the method /// returns true if there were changes from the original `typeA`. /// </summary> private static bool MergeEquivalentTypeArguments( NamedTypeSymbol typeA, NamedTypeSymbol typeB, VarianceKind variance, ArrayBuilder<TypeParameterSymbol> allTypeParameters, ArrayBuilder<TypeWithAnnotations> allTypeArguments) { Debug.Assert(typeA.IsGenericType); Debug.Assert(typeA.Equals(typeB, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // Tuple types act as covariant when merging equivalent types. bool isTuple = typeA.IsTupleType; var definition = typeA.OriginalDefinition; bool haveChanges = false; while (true) { var typeParameters = definition.TypeParameters; if (typeParameters.Length > 0) { var typeArgumentsA = typeA.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var typeArgumentsB = typeB.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; allTypeParameters.AddRange(typeParameters); for (int i = 0; i < typeArgumentsA.Length; i++) { TypeWithAnnotations typeArgumentA = typeArgumentsA[i]; TypeWithAnnotations typeArgumentB = typeArgumentsB[i]; VarianceKind typeArgumentVariance = GetTypeArgumentVariance(variance, isTuple ? VarianceKind.Out : typeParameters[i].Variance); TypeWithAnnotations merged = typeArgumentA.MergeEquivalentTypes(typeArgumentB, typeArgumentVariance); allTypeArguments.Add(merged); if (!typeArgumentA.IsSameAs(merged)) { haveChanges = true; } } } definition = definition.ContainingType; if (definition is null) { break; } typeA = typeA.ContainingType; typeB = typeB.ContainingType; variance = VarianceKind.None; } return haveChanges; } private static VarianceKind GetTypeArgumentVariance(VarianceKind typeVariance, VarianceKind typeParameterVariance) { switch (typeVariance) { case VarianceKind.In: switch (typeParameterVariance) { case VarianceKind.In: return VarianceKind.Out; case VarianceKind.Out: return VarianceKind.In; default: return VarianceKind.None; } case VarianceKind.Out: return typeParameterVariance; default: return VarianceKind.None; } } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments">The immediate type arguments to be replaced for type /// parameters in the type.</param> public NamedTypeSymbol Construct(params TypeSymbol[] typeArguments) { // https://github.com/dotnet/roslyn/issues/30064: We should fix the callers to pass TypeWithAnnotations[] instead of TypeSymbol[]. return ConstructWithoutModifiers(typeArguments.AsImmutableOrNull(), false); } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments">The immediate type arguments to be replaced for type /// parameters in the type.</param> public NamedTypeSymbol Construct(ImmutableArray<TypeSymbol> typeArguments) { // https://github.com/dotnet/roslyn/issues/30064: We should fix the callers to pass ImmutableArray<TypeWithAnnotations> instead of ImmutableArray<TypeSymbol>. return ConstructWithoutModifiers(typeArguments, false); } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments"></param> public NamedTypeSymbol Construct(IEnumerable<TypeSymbol> typeArguments) { // https://github.com/dotnet/roslyn/issues/30064: We should fix the callers to pass IEnumerable<TypeWithAnnotations> instead of IEnumerable<TypeSymbol>. return ConstructWithoutModifiers(typeArguments.AsImmutableOrNull(), false); } /// <summary> /// Returns an unbound generic type of this named type. /// </summary> public NamedTypeSymbol ConstructUnboundGenericType() { return OriginalDefinition.AsUnboundGenericType(); } internal NamedTypeSymbol GetUnboundGenericTypeOrSelf() { if (!this.IsGenericType) { return this; } return this.ConstructUnboundGenericType(); } /// <summary> /// Gets a value indicating whether this type has an EmbeddedAttribute or not. /// </summary> internal abstract bool HasCodeAnalysisEmbeddedAttribute { get; } /// <summary> /// Gets a value indicating whether this type has System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute or not. /// </summary> internal abstract bool IsInterpolatedStringHandlerType { get; } internal static readonly Func<TypeWithAnnotations, bool> TypeWithAnnotationsIsNullFunction = type => !type.HasType; internal static readonly Func<TypeWithAnnotations, bool> TypeWithAnnotationsIsErrorType = type => type.HasType && type.Type.IsErrorType(); private NamedTypeSymbol ConstructWithoutModifiers(ImmutableArray<TypeSymbol> typeArguments, bool unbound) { ImmutableArray<TypeWithAnnotations> modifiedArguments; if (typeArguments.IsDefault) { modifiedArguments = default(ImmutableArray<TypeWithAnnotations>); } else { modifiedArguments = typeArguments.SelectAsArray(t => TypeWithAnnotations.Create(t)); } return Construct(modifiedArguments, unbound); } internal NamedTypeSymbol Construct(ImmutableArray<TypeWithAnnotations> typeArguments) { return Construct(typeArguments, unbound: false); } internal NamedTypeSymbol Construct(ImmutableArray<TypeWithAnnotations> typeArguments, bool unbound) { if (!ReferenceEquals(this, ConstructedFrom)) { throw new InvalidOperationException(CSharpResources.CannotCreateConstructedFromConstructed); } if (this.Arity == 0) { throw new InvalidOperationException(CSharpResources.CannotCreateConstructedFromNongeneric); } if (typeArguments.IsDefault) { throw new ArgumentNullException(nameof(typeArguments)); } if (typeArguments.Any(TypeWithAnnotationsIsNullFunction)) { throw new ArgumentException(CSharpResources.TypeArgumentCannotBeNull, nameof(typeArguments)); } if (typeArguments.Length != this.Arity) { throw new ArgumentException(CSharpResources.WrongNumberOfTypeArguments, nameof(typeArguments)); } Debug.Assert(!unbound || typeArguments.All(TypeWithAnnotationsIsErrorType)); if (ConstructedNamedTypeSymbol.TypeParametersMatchTypeArguments(this.TypeParameters, typeArguments)) { return this; } return this.ConstructCore(typeArguments, unbound); } protected virtual NamedTypeSymbol ConstructCore(ImmutableArray<TypeWithAnnotations> typeArguments, bool unbound) { return new ConstructedNamedTypeSymbol(this, typeArguments, unbound); } /// <summary> /// True if this type or some containing type has type parameters. /// </summary> public bool IsGenericType { get { for (var current = this; !ReferenceEquals(current, null); current = current.ContainingType) { if (current.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length != 0) { return true; } } return false; } } /// <summary> /// True if this is a reference to an <em>unbound</em> generic type. These occur only /// within a <c>typeof</c> expression. A generic type is considered <em>unbound</em> /// if all of the type argument lists in its fully qualified name are empty. /// Note that the type arguments of an unbound generic type will be returned as error /// types because they do not really have type arguments. An unbound generic type /// yields null for its BaseType and an empty result for its Interfaces. /// </summary> public virtual bool IsUnboundGenericType { get { return false; } } // Given C<int>.D<string, double>, yields { int, string, double } internal void GetAllTypeArguments(ArrayBuilder<TypeSymbol> builder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var outer = ContainingType; if (!ReferenceEquals(outer, null)) { outer.GetAllTypeArguments(builder, ref useSiteInfo); } foreach (var argument in TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { builder.Add(argument.Type); } } internal ImmutableArray<TypeWithAnnotations> GetAllTypeArguments(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayBuilder<TypeWithAnnotations> builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllTypeArguments(builder, ref useSiteInfo); return builder.ToImmutableAndFree(); } internal void GetAllTypeArguments(ArrayBuilder<TypeWithAnnotations> builder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var outer = ContainingType; if (!ReferenceEquals(outer, null)) { outer.GetAllTypeArguments(builder, ref useSiteInfo); } builder.AddRange(TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); } internal void GetAllTypeArgumentsNoUseSiteDiagnostics(ArrayBuilder<TypeWithAnnotations> builder) { ContainingType?.GetAllTypeArgumentsNoUseSiteDiagnostics(builder); builder.AddRange(TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); } internal int AllTypeArgumentCount() { int count = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; var outer = ContainingType; if (!ReferenceEquals(outer, null)) { count += outer.AllTypeArgumentCount(); } return count; } internal ImmutableArray<TypeWithAnnotations> GetTypeParametersAsTypeArguments() { return TypeMap.TypeParametersAsTypeSymbolsWithAnnotations(this.TypeParameters); } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new virtual NamedTypeSymbol OriginalDefinition { get { return this; } } protected sealed override TypeSymbol OriginalTypeSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// Returns the map from type parameters to type arguments. /// If this is not a generic type instantiation, returns null. /// The map targets the original definition of the type. /// </summary> internal virtual TypeMap TypeSubstitution { get { return null; } } internal virtual NamedTypeSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(this.IsDefinition); Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol.OriginalDefinition)); return newOwner.IsDefinition ? this : new SubstitutedNestedTypeSymbol((SubstitutedNamedTypeSymbol)newOwner, this); } #region Use-Site Diagnostics internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { UseSiteInfo<AssemblySymbol> result = new UseSiteInfo<AssemblySymbol>(PrimaryDependency); if (this.IsDefinition) { return result; } // Check definition, type arguments if (!DeriveUseSiteInfoFromType(ref result, this.OriginalDefinition)) { DeriveUseSiteDiagnosticFromTypeArguments(ref result); } return result; } private bool DeriveUseSiteDiagnosticFromTypeArguments(ref UseSiteInfo<AssemblySymbol> result) { NamedTypeSymbol currentType = this; do { foreach (TypeWithAnnotations arg in currentType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { if (DeriveUseSiteInfoFromType(ref result, arg, AllowedRequiredModifierType.None)) { return true; } } currentType = currentType.ContainingType; } while (currentType?.IsDefinition == false); return false; } internal DiagnosticInfo CalculateUseSiteDiagnostic() { DiagnosticInfo result = null; // Check base type. if (MergeUseSiteDiagnostics(ref result, DeriveUseSiteDiagnosticFromBase())) { return result; } // If we reach a type (Me) that is in an assembly with unified references, // we check if that type definition depends on a type from a unified reference. if (this.ContainingModule.HasUnifiedReferences) { HashSet<TypeSymbol> unificationCheckedTypes = null; if (GetUnificationUseSiteDiagnosticRecursive(ref result, this, ref unificationCheckedTypes)) { return result; } } return result; } private DiagnosticInfo DeriveUseSiteDiagnosticFromBase() { NamedTypeSymbol @base = this.BaseTypeNoUseSiteDiagnostics; while ((object)@base != null) { if (@base.IsErrorType() && @base is NoPiaIllegalGenericInstantiationSymbol) { return @base.GetUseSiteInfo().DiagnosticInfo; } @base = @base.BaseTypeNoUseSiteDiagnostics; } return null; } internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { if (!this.MarkCheckedIfNecessary(ref checkedTypes)) { return false; } Debug.Assert(owner.ContainingModule.HasUnifiedReferences); if (owner.ContainingModule.GetUnificationUseSiteDiagnostic(ref result, this)) { return true; } // We recurse into base types, interfaces and type *parameters* to check for // problems with constraints. We recurse into type *arguments* in the overload // in ConstructedNamedTypeSymbol. // // When we are binding a name with a nested type, Goo.Bar, then we ask for // use-site errors to be reported on both Goo and Goo.Bar. Therefore we should // not recurse into the containing type here; doing so will result in errors // being reported twice if Goo is bad. var @base = this.BaseTypeNoUseSiteDiagnostics; if ((object)@base != null && @base.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } return GetUnificationUseSiteDiagnosticRecursive(ref result, this.InterfacesNoUseSiteDiagnostics(), owner, ref checkedTypes) || GetUnificationUseSiteDiagnosticRecursive(ref result, this.TypeParameters, owner, ref checkedTypes); } #endregion /// <summary> /// True if the type itself is excluded from code coverage instrumentation. /// True for source types marked with <see cref="AttributeDescription.ExcludeFromCodeCoverageAttribute"/>. /// </summary> internal virtual bool IsDirectlyExcludedFromCodeCoverage { get => false; } /// <summary> /// True if this symbol has a special name (metadata flag SpecialName is set). /// </summary> internal abstract bool HasSpecialName { get; } /// <summary> /// Returns a flag indicating whether this symbol is ComImport. /// </summary> /// <remarks> /// A type can me marked as a ComImport type in source by applying the <see cref="System.Runtime.InteropServices.ComImportAttribute"/> /// </remarks> internal abstract bool IsComImport { get; } /// <summary> /// True if the type is a Windows runtime type. /// </summary> /// <remarks> /// A type can me marked as a Windows runtime type in source by applying the WindowsRuntimeImportAttribute. /// WindowsRuntimeImportAttribute is a pseudo custom attribute defined as an internal class in System.Runtime.InteropServices.WindowsRuntime namespace. /// This is needed to mark Windows runtime types which are redefined in mscorlib.dll and System.Runtime.WindowsRuntime.dll. /// These two assemblies are special as they implement the CLR's support for WinRT. /// </remarks> internal abstract bool IsWindowsRuntimeImport { get; } /// <summary> /// True if the type should have its WinRT interfaces projected onto .NET types and /// have missing .NET interface members added to the type. /// </summary> internal abstract bool ShouldAddWinRTMembers { get; } /// <summary> /// Returns a flag indicating whether this symbol has at least one applied/inherited conditional attribute. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal bool IsConditional { get { if (this.GetAppliedConditionalSymbols().Any()) { return true; } // Conditional attributes are inherited by derived types. var baseType = this.BaseTypeNoUseSiteDiagnostics; return (object)baseType != null ? baseType.IsConditional : false; } } /// <summary> /// True if the type is serializable (has Serializable metadata flag). /// </summary> public abstract bool IsSerializable { get; } /// <summary> /// Returns true if locals are to be initialized /// </summary> public abstract bool AreLocalsZeroed { get; } /// <summary> /// Type layout information (ClassLayout metadata and layout kind flags). /// </summary> internal abstract TypeLayout Layout { get; } /// <summary> /// The default charset used for type marshalling. /// Can be changed via <see cref="DefaultCharSetAttribute"/> applied on the containing module. /// </summary> protected CharSet DefaultMarshallingCharSet { get { return this.GetEffectiveDefaultMarshallingCharSet() ?? CharSet.Ansi; } } /// <summary> /// Marshalling charset of string data fields within the type (string formatting flags in metadata). /// </summary> internal abstract CharSet MarshallingCharSet { get; } /// <summary> /// True if the type has declarative security information (HasSecurity flags). /// </summary> internal abstract bool HasDeclarativeSecurity { get; } /// <summary> /// Declaration security information associated with this type, or null if there is none. /// </summary> internal abstract IEnumerable<Cci.SecurityAttribute> GetSecurityInformation(); /// <summary> /// Returns a sequence of preprocessor symbols specified in <see cref="ConditionalAttribute"/> applied on this symbol, or null if there are none. /// </summary> internal abstract ImmutableArray<string> GetAppliedConditionalSymbols(); /// <summary> /// If <see cref="CoClassAttribute"/> was applied to the type and the attribute argument is a valid named type argument, i.e. accessible class type, then it returns the type symbol for the argument. /// Otherwise, returns null. /// </summary> /// <remarks> /// <para> /// This property invokes force completion of attributes. If you are accessing this property /// from the binder, make sure that we are not binding within an Attribute context. /// This could lead to a possible cycle in attribute binding. /// We can avoid this cycle by first checking if we are within the context of an Attribute argument, /// i.e. if(!binder.InAttributeArgument) { ... namedType.ComImportCoClass ... } /// </para> /// <para> /// CONSIDER: We can remove the above restriction and possibility of cycle if we do an /// early binding of some well known attributes. /// </para> /// </remarks> internal virtual NamedTypeSymbol ComImportCoClass { get { return null; } } /// <summary> /// If class represents fixed buffer, this property returns the FixedElementField /// </summary> internal virtual FieldSymbol FixedElementField { get { return null; } } /// <summary> /// Requires less computation than <see cref="TypeSymbol.TypeKind"/> == <see cref="TypeKind.Interface"/>. /// </summary> /// <remarks> /// Metadata types need to compute their base types in order to know their TypeKinds, and that can lead /// to cycles if base types are already being computed. /// </remarks> /// <returns>True if this is an interface type.</returns> internal abstract bool IsInterface { get; } /// <summary> /// Verify if the given type can be used to back a tuple type /// and return cardinality of that tuple type in <paramref name="tupleCardinality"/>. /// </summary> /// <param name="tupleCardinality">If method returns true, contains cardinality of the compatible tuple type.</param> /// <returns></returns> internal bool IsTupleTypeOfCardinality(out int tupleCardinality) { // Should this be optimized for perf (caching for VT<0> to VT<7>, etc.)? if (!IsUnboundGenericType && ContainingSymbol?.Kind == SymbolKind.Namespace && ContainingNamespace.ContainingNamespace?.IsGlobalNamespace == true && Name == ValueTupleTypeName && ContainingNamespace.Name == MetadataHelpers.SystemString) { int arity = Arity; if (arity >= 0 && arity < ValueTupleRestPosition) { tupleCardinality = arity; return true; } else if (arity == ValueTupleRestPosition && !IsDefinition) { // Skip through "Rest" extensions TypeSymbol typeToCheck = this; int levelsOfNesting = 0; do { levelsOfNesting++; typeToCheck = ((NamedTypeSymbol)typeToCheck).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[ValueTupleRestPosition - 1].Type; } while (Equals(typeToCheck.OriginalDefinition, this.OriginalDefinition, TypeCompareKind.ConsiderEverything) && !typeToCheck.IsDefinition); arity = (typeToCheck as NamedTypeSymbol)?.Arity ?? 0; if (arity > 0 && arity < ValueTupleRestPosition && ((NamedTypeSymbol)typeToCheck).IsTupleTypeOfCardinality(out tupleCardinality)) { Debug.Assert(tupleCardinality < ValueTupleRestPosition); tupleCardinality += (ValueTupleRestPosition - 1) * levelsOfNesting; return true; } } } tupleCardinality = 0; return false; } /// <summary> /// Returns an instance of a symbol that represents a native integer /// if this underlying symbol represents System.IntPtr or System.UIntPtr. /// For other symbols, throws <see cref="System.InvalidOperationException"/>. /// </summary> internal abstract NamedTypeSymbol AsNativeInteger(); /// <summary> /// If this is a native integer, returns the symbol for the underlying type, /// either <see cref="System.IntPtr"/> or <see cref="System.UIntPtr"/>. /// Otherwise, returns null. /// </summary> internal abstract NamedTypeSymbol NativeIntegerUnderlyingType { get; } /// <summary> /// Returns true if the type is defined in source and contains field initializers. /// This method is only valid on a definition. /// </summary> internal virtual bool HasFieldInitializers() { Debug.Assert(IsDefinition); return false; } protected override ISymbol CreateISymbol() { return new PublicModel.NonErrorNamedTypeSymbol(this, DefaultNullableAnnotation); } protected override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { Debug.Assert(nullableAnnotation != DefaultNullableAnnotation); return new PublicModel.NonErrorNamedTypeSymbol(this, nullableAnnotation); } INamedTypeSymbolInternal INamedTypeSymbolInternal.EnumUnderlyingType { get { return this.EnumUnderlyingType; } } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./eng/common/sdl/configure-sdl-tool.ps1
Param( [string] $GuardianCliLocation, [string] $WorkingDirectory, [string] $TargetDirectory, [string] $GdnFolder, # The list of Guardian tools to configure. For each object in the array: # - If the item is a [hashtable], it must contain these entries: # - Name = The tool name as Guardian knows it. # - Scenario = (Optional) Scenario-specific name for this configuration entry. It must be unique # among all tool entries with the same Name. # - Args = (Optional) Array of Guardian tool configuration args, like '@("Target > C:\temp")' # - If the item is a [string] $v, it is treated as '@{ Name="$v" }' [object[]] $ToolsList, [string] $GuardianLoggerLevel='Standard', # Optional: Additional params to add to any tool using CredScan. [string[]] $CrScanAdditionalRunConfigParams, # Optional: Additional params to add to any tool using PoliCheck. [string[]] $PoliCheckAdditionalRunConfigParams ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 $disableConfigureToolsetImport = $true $global:LASTEXITCODE = 0 try { # `tools.ps1` checks $ci to perform some actions. Since the SDL # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true . $PSScriptRoot\..\tools.ps1 # Normalize tools list: all in [hashtable] form with defined values for each key. $ToolsList = $ToolsList | ForEach-Object { if ($_ -is [string]) { $_ = @{ Name = $_ } } if (-not ($_['Scenario'])) { $_.Scenario = "" } if (-not ($_['Args'])) { $_.Args = @() } $_ } Write-Host "List of tools to configure:" $ToolsList | ForEach-Object { $_ | Out-String | Write-Host } # We store config files in the r directory of .gdn $gdnConfigPath = Join-Path $GdnFolder 'r' $ValidPath = Test-Path $GuardianCliLocation if ($ValidPath -eq $False) { Write-PipelineTelemetryError -Force -Category 'Sdl' -Message "Invalid Guardian CLI Location." ExitWithExitCode 1 } foreach ($tool in $ToolsList) { # Put together the name and scenario to make a unique key. $toolConfigName = $tool.Name if ($tool.Scenario) { $toolConfigName += "_" + $tool.Scenario } Write-Host "=== Configuring $toolConfigName..." $gdnConfigFile = Join-Path $gdnConfigPath "$toolConfigName-configure.gdnconfig" # For some tools, add default and automatic args. if ($tool.Name -eq 'credscan') { if ($targetDirectory) { $tool.Args += "TargetDirectory < $TargetDirectory" } $tool.Args += "OutputType < pre" $tool.Args += $CrScanAdditionalRunConfigParams } elseif ($tool.Name -eq 'policheck') { if ($targetDirectory) { $tool.Args += "Target < $TargetDirectory" } $tool.Args += $PoliCheckAdditionalRunConfigParams } # Create variable pointing to the args array directly so we can use splat syntax later. $toolArgs = $tool.Args # Configure the tool. If args array is provided or the current tool has some default arguments # defined, add "--args" and splat each element on the end. Arg format is "{Arg id} < {Value}", # one per parameter. Doc page for "guardian configure": # https://dev.azure.com/securitytools/SecurityIntegration/_wiki/wikis/Guardian/1395/configure Exec-BlockVerbosely { & $GuardianCliLocation configure ` --working-directory $WorkingDirectory ` --tool $tool.Name ` --output-path $gdnConfigFile ` --logger-level $GuardianLoggerLevel ` --noninteractive ` --force ` $(if ($toolArgs) { "--args" }) @toolArgs Exit-IfNZEC "Sdl" } Write-Host "Created '$toolConfigName' configuration file: $gdnConfigFile" } } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 }
Param( [string] $GuardianCliLocation, [string] $WorkingDirectory, [string] $TargetDirectory, [string] $GdnFolder, # The list of Guardian tools to configure. For each object in the array: # - If the item is a [hashtable], it must contain these entries: # - Name = The tool name as Guardian knows it. # - Scenario = (Optional) Scenario-specific name for this configuration entry. It must be unique # among all tool entries with the same Name. # - Args = (Optional) Array of Guardian tool configuration args, like '@("Target > C:\temp")' # - If the item is a [string] $v, it is treated as '@{ Name="$v" }' [object[]] $ToolsList, [string] $GuardianLoggerLevel='Standard', # Optional: Additional params to add to any tool using CredScan. [string[]] $CrScanAdditionalRunConfigParams, # Optional: Additional params to add to any tool using PoliCheck. [string[]] $PoliCheckAdditionalRunConfigParams ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 $disableConfigureToolsetImport = $true $global:LASTEXITCODE = 0 try { # `tools.ps1` checks $ci to perform some actions. Since the SDL # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true . $PSScriptRoot\..\tools.ps1 # Normalize tools list: all in [hashtable] form with defined values for each key. $ToolsList = $ToolsList | ForEach-Object { if ($_ -is [string]) { $_ = @{ Name = $_ } } if (-not ($_['Scenario'])) { $_.Scenario = "" } if (-not ($_['Args'])) { $_.Args = @() } $_ } Write-Host "List of tools to configure:" $ToolsList | ForEach-Object { $_ | Out-String | Write-Host } # We store config files in the r directory of .gdn $gdnConfigPath = Join-Path $GdnFolder 'r' $ValidPath = Test-Path $GuardianCliLocation if ($ValidPath -eq $False) { Write-PipelineTelemetryError -Force -Category 'Sdl' -Message "Invalid Guardian CLI Location." ExitWithExitCode 1 } foreach ($tool in $ToolsList) { # Put together the name and scenario to make a unique key. $toolConfigName = $tool.Name if ($tool.Scenario) { $toolConfigName += "_" + $tool.Scenario } Write-Host "=== Configuring $toolConfigName..." $gdnConfigFile = Join-Path $gdnConfigPath "$toolConfigName-configure.gdnconfig" # For some tools, add default and automatic args. if ($tool.Name -eq 'credscan') { if ($targetDirectory) { $tool.Args += "TargetDirectory < $TargetDirectory" } $tool.Args += "OutputType < pre" $tool.Args += $CrScanAdditionalRunConfigParams } elseif ($tool.Name -eq 'policheck') { if ($targetDirectory) { $tool.Args += "Target < $TargetDirectory" } $tool.Args += $PoliCheckAdditionalRunConfigParams } # Create variable pointing to the args array directly so we can use splat syntax later. $toolArgs = $tool.Args # Configure the tool. If args array is provided or the current tool has some default arguments # defined, add "--args" and splat each element on the end. Arg format is "{Arg id} < {Value}", # one per parameter. Doc page for "guardian configure": # https://dev.azure.com/securitytools/SecurityIntegration/_wiki/wikis/Guardian/1395/configure Exec-BlockVerbosely { & $GuardianCliLocation configure ` --working-directory $WorkingDirectory ` --tool $tool.Name ` --output-path $gdnConfigFile ` --logger-level $GuardianLoggerLevel ` --noninteractive ` --force ` $(if ($toolArgs) { "--args" }) @toolArgs Exit-IfNZEC "Sdl" } Write-Host "Created '$toolConfigName' configuration file: $gdnConfigFile" } } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/CodeStyle/Core/Analyzers/PublicAPI.Unshipped.txt
Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.AddAccessor = 26 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Attribute = 22 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Class = 2 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.CompilationUnit = 1 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Constructor = 10 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.ConversionOperator = 9 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.CustomEvent = 17 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Delegate = 6 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Destructor = 11 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Enum = 5 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.EnumMember = 15 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Event = 16 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Field = 12 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.GetAccessor = 24 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Indexer = 14 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Interface = 4 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.LambdaExpression = 23 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Method = 7 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Namespace = 18 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.NamespaceImport = 19 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.None = 0 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Operator = 8 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Parameter = 20 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Property = 13 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.RaiseAccessor = 28 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.RecordClass = 29 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.RemoveAccessor = 27 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.SetAccessor = 25 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Struct = 3 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Variable = 21 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.DeclarationModifiers() -> void Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Equals(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers modifiers) -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsAbstract.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsAsync.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsConst.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsExtern.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsNew.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsOverride.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsPartial.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsReadOnly.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsRef.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsSealed.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsStatic.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsUnsafe.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsVirtual.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsVolatile.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsWithEvents.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsWriteOnly.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithAsync(bool isAsync) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsAbstract(bool isAbstract) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsConst(bool isConst) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsExtern(bool isExtern) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsNew(bool isNew) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsOverride(bool isOverride) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsReadOnly(bool isReadOnly) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsRef(bool isRef) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsSealed(bool isSealed) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsStatic(bool isStatic) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsUnsafe(bool isUnsafe) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsVirtual(bool isVirtual) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsVolatile(bool isVolatile) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsWriteOnly(bool isWriteOnly) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithPartial(bool isPartial) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithWithEvents(bool withEvents) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers override Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Equals(object obj) -> bool override Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.GetHashCode() -> int override Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.ToString() -> string static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Abstract.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Async.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Const.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Extern.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.From(Microsoft.CodeAnalysis.ISymbol symbol) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.New.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.None.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator !=(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> bool static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator &(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator +(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator -(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator ==(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> bool static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator |(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Override.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Partial.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.ReadOnly.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Ref.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Sealed.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Static.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.TryParse(string value, out Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers modifiers) -> bool static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Unsafe.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Virtual.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Volatile.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithEvents.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WriteOnly.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.AddAccessor = 26 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Attribute = 22 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Class = 2 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.CompilationUnit = 1 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Constructor = 10 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.ConversionOperator = 9 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.CustomEvent = 17 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Delegate = 6 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Destructor = 11 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Enum = 5 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.EnumMember = 15 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Event = 16 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Field = 12 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.GetAccessor = 24 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Indexer = 14 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Interface = 4 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.LambdaExpression = 23 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Method = 7 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Namespace = 18 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.NamespaceImport = 19 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.None = 0 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Operator = 8 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Parameter = 20 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Property = 13 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.RaiseAccessor = 28 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.RecordClass = 29 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.RemoveAccessor = 27 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.SetAccessor = 25 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Struct = 3 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind.Variable = 21 -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationKind Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.DeclarationModifiers() -> void Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Equals(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers modifiers) -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsAbstract.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsAsync.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsConst.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsExtern.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsNew.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsOverride.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsPartial.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsReadOnly.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsRef.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsSealed.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsStatic.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsUnsafe.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsVirtual.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsVolatile.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsWithEvents.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.IsWriteOnly.get -> bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithAsync(bool isAsync) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsAbstract(bool isAbstract) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsConst(bool isConst) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsExtern(bool isExtern) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsNew(bool isNew) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsOverride(bool isOverride) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsReadOnly(bool isReadOnly) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsRef(bool isRef) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsSealed(bool isSealed) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsStatic(bool isStatic) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsUnsafe(bool isUnsafe) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsVirtual(bool isVirtual) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsVolatile(bool isVolatile) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsWriteOnly(bool isWriteOnly) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithPartial(bool isPartial) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithWithEvents(bool withEvents) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers override Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Equals(object obj) -> bool override Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.GetHashCode() -> int override Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.ToString() -> string static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Abstract.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Async.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Const.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Extern.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.From(Microsoft.CodeAnalysis.ISymbol symbol) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.New.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.None.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator !=(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> bool static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator &(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator +(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator -(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator ==(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> bool static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator |(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Override.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Partial.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.ReadOnly.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Ref.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Sealed.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Static.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.TryParse(string value, out Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers modifiers) -> bool static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Unsafe.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Virtual.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Volatile.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithEvents.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WriteOnly.get -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/CodeStyle/VisualBasic/Analyzers/PublicAPI.Shipped.txt
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Scripting/CoreTest.Desktop/GlobalAssemblyCacheTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using System.Reflection; using Xunit; using System.Collections.Immutable; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.UnitTests { public class GlobalAssemblyCacheTests { [Fact] public void GetAssemblyIdentities() { var gac = GlobalAssemblyCache.Instance; AssemblyIdentity[] names; names = gac.GetAssemblyIdentities(new AssemblyName("mscorlib")).ToArray(); Assert.True(names.Length >= 1, "At least 1 mscorlib"); foreach (var name in names) { Assert.Equal("mscorlib", name.Name); } names = gac.GetAssemblyIdentities(new AssemblyName("mscorlib"), ImmutableArray.Create(ProcessorArchitecture.MSIL, ProcessorArchitecture.X86)).ToArray(); Assert.True(names.Length >= 1, "At least one 32bit mscorlib"); foreach (var name in names) { Assert.Equal("mscorlib", name.Name); } names = gac.GetAssemblyIdentities("mscorlib").ToArray(); Assert.True(names.Length >= 1, "At least 1 mscorlib"); foreach (var name in names) { Assert.Equal("mscorlib", name.Name); } names = gac.GetAssemblyIdentities("System.Core, Version=4.0.0.0").ToArray(); Assert.True(names.Length >= 1, "At least System.Core"); foreach (var name in names) { Assert.Equal("System.Core", name.Name); Assert.Equal(new Version(4, 0, 0, 0), name.Version); Assert.True(name.GetDisplayName().Contains("PublicKeyToken=b77a5c561934e089"), "PublicKeyToken matches"); } names = gac.GetAssemblyIdentities("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").ToArray(); Assert.True(names.Length >= 1, "At least System.Core"); foreach (var name in names) { Assert.Equal("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", name.GetDisplayName()); } var n = new AssemblyName("System.Core"); n.Version = new Version(4, 0, 0, 0); n.SetPublicKeyToken(new byte[] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 }); names = gac.GetAssemblyIdentities(n).ToArray(); Assert.True(names.Length >= 1, "At least System.Core"); foreach (var name in names) { Assert.Equal("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", name.GetDisplayName()); } names = gac.GetAssemblyIdentities("x\u0002").ToArray(); Assert.Equal(0, names.Length); names = gac.GetAssemblyIdentities("\0").ToArray(); Assert.Equal(0, names.Length); names = gac.GetAssemblyIdentities("xxxx\0xxxxx").ToArray(); Assert.Equal(0, names.Length); // fusion API CreateAssemblyEnum returns S_FALSE for this name names = gac.GetAssemblyIdentities("nonexistingassemblyname" + Guid.NewGuid().ToString()).ToArray(); Assert.Equal(0, names.Length); } [Fact] public void GetFacadeAssemblyIdentities() { var gac = GlobalAssemblyCache.Instance; AssemblyIdentity[] names; // One netstandard.dll should resolve from Facades on Mono names = gac.GetAssemblyIdentities(new AssemblyName("netstandard")).ToArray(); Assert.Collection(names, name => { Assert.Equal("netstandard", name.Name); Assert.True(name.Version >= new Version("2.0.0.0"), "netstandard version must be >= 2.0.0.0"); }); } [ClrOnlyFact(ClrOnlyReason.Fusion)] public void AssemblyAndGacLocation() { var names = ClrGlobalAssemblyCache.GetAssemblyObjects(partialNameFilter: null, architectureFilter: default(ImmutableArray<ProcessorArchitecture>)).ToArray(); Assert.True(names.Length > 100, "There are at least 100 assemblies in the GAC"); var gacLocationsUpper = GlobalAssemblyCacheLocation.RootLocations.Select(location => location.ToUpper()); foreach (var name in names) { string location = ClrGlobalAssemblyCache.GetAssemblyLocation(name); Assert.NotNull(location); Assert.True(gacLocationsUpper.Any(gac => location.StartsWith(gac, StringComparison.OrdinalIgnoreCase)), "Path within some GAC root"); Assert.Equal(Path.GetFullPath(location), location); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using System.Reflection; using Xunit; using System.Collections.Immutable; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.UnitTests { public class GlobalAssemblyCacheTests { [Fact] public void GetAssemblyIdentities() { var gac = GlobalAssemblyCache.Instance; AssemblyIdentity[] names; names = gac.GetAssemblyIdentities(new AssemblyName("mscorlib")).ToArray(); Assert.True(names.Length >= 1, "At least 1 mscorlib"); foreach (var name in names) { Assert.Equal("mscorlib", name.Name); } names = gac.GetAssemblyIdentities(new AssemblyName("mscorlib"), ImmutableArray.Create(ProcessorArchitecture.MSIL, ProcessorArchitecture.X86)).ToArray(); Assert.True(names.Length >= 1, "At least one 32bit mscorlib"); foreach (var name in names) { Assert.Equal("mscorlib", name.Name); } names = gac.GetAssemblyIdentities("mscorlib").ToArray(); Assert.True(names.Length >= 1, "At least 1 mscorlib"); foreach (var name in names) { Assert.Equal("mscorlib", name.Name); } names = gac.GetAssemblyIdentities("System.Core, Version=4.0.0.0").ToArray(); Assert.True(names.Length >= 1, "At least System.Core"); foreach (var name in names) { Assert.Equal("System.Core", name.Name); Assert.Equal(new Version(4, 0, 0, 0), name.Version); Assert.True(name.GetDisplayName().Contains("PublicKeyToken=b77a5c561934e089"), "PublicKeyToken matches"); } names = gac.GetAssemblyIdentities("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").ToArray(); Assert.True(names.Length >= 1, "At least System.Core"); foreach (var name in names) { Assert.Equal("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", name.GetDisplayName()); } var n = new AssemblyName("System.Core"); n.Version = new Version(4, 0, 0, 0); n.SetPublicKeyToken(new byte[] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 }); names = gac.GetAssemblyIdentities(n).ToArray(); Assert.True(names.Length >= 1, "At least System.Core"); foreach (var name in names) { Assert.Equal("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", name.GetDisplayName()); } names = gac.GetAssemblyIdentities("x\u0002").ToArray(); Assert.Equal(0, names.Length); names = gac.GetAssemblyIdentities("\0").ToArray(); Assert.Equal(0, names.Length); names = gac.GetAssemblyIdentities("xxxx\0xxxxx").ToArray(); Assert.Equal(0, names.Length); // fusion API CreateAssemblyEnum returns S_FALSE for this name names = gac.GetAssemblyIdentities("nonexistingassemblyname" + Guid.NewGuid().ToString()).ToArray(); Assert.Equal(0, names.Length); } [Fact] public void GetFacadeAssemblyIdentities() { var gac = GlobalAssemblyCache.Instance; AssemblyIdentity[] names; // One netstandard.dll should resolve from Facades on Mono names = gac.GetAssemblyIdentities(new AssemblyName("netstandard")).ToArray(); Assert.Collection(names, name => { Assert.Equal("netstandard", name.Name); Assert.True(name.Version >= new Version("2.0.0.0"), "netstandard version must be >= 2.0.0.0"); }); } [ClrOnlyFact(ClrOnlyReason.Fusion)] public void AssemblyAndGacLocation() { var names = ClrGlobalAssemblyCache.GetAssemblyObjects(partialNameFilter: null, architectureFilter: default(ImmutableArray<ProcessorArchitecture>)).ToArray(); Assert.True(names.Length > 100, "There are at least 100 assemblies in the GAC"); var gacLocationsUpper = GlobalAssemblyCacheLocation.RootLocations.Select(location => location.ToUpper()); foreach (var name in names) { string location = ClrGlobalAssemblyCache.GetAssemblyLocation(name); Assert.NotNull(location); Assert.True(gacLocationsUpper.Any(gac => location.StartsWith(gac, StringComparison.OrdinalIgnoreCase)), "Path within some GAC root"); Assert.Equal(Path.GetFullPath(location), location); } } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Workspaces/Core/Portable/Remote/WellKnownSynchronizationKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Serialization { // TODO: Kind might not actually needed. see whether we can get rid of this internal enum WellKnownSynchronizationKind { Null, SolutionState, ProjectState, DocumentState, ChecksumCollection, SolutionAttributes, ProjectAttributes, DocumentAttributes, SourceGeneratedDocumentIdentity, CompilationOptions, ParseOptions, ProjectReference, MetadataReference, AnalyzerReference, SourceText, OptionSet, SerializableSourceText, // SyntaxTreeIndex, SymbolTreeInfo, ProjectReferenceChecksumCollection, MetadataReferenceChecksumCollection, AnalyzerReferenceChecksumCollection, TextDocumentChecksumCollection, DocumentChecksumCollection, AnalyzerConfigDocumentChecksumCollection, ProjectChecksumCollection, SolutionStateChecksums, ProjectStateChecksums, DocumentStateChecksums, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Serialization { // TODO: Kind might not actually needed. see whether we can get rid of this internal enum WellKnownSynchronizationKind { Null, SolutionState, ProjectState, DocumentState, ChecksumCollection, SolutionAttributes, ProjectAttributes, DocumentAttributes, SourceGeneratedDocumentIdentity, CompilationOptions, ParseOptions, ProjectReference, MetadataReference, AnalyzerReference, SourceText, OptionSet, SerializableSourceText, // SyntaxTreeIndex, SymbolTreeInfo, ProjectReferenceChecksumCollection, MetadataReferenceChecksumCollection, AnalyzerReferenceChecksumCollection, TextDocumentChecksumCollection, DocumentChecksumCollection, AnalyzerConfigDocumentChecksumCollection, ProjectChecksumCollection, SolutionStateChecksums, ProjectStateChecksums, DocumentStateChecksums, } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IAnonymousFunctionExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IAnonymousFunctionExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action x = () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action x = () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action x = () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree_JustBindingLambdaReturnsOnlyIAnonymousFunctionExpression() { string source = @" using System; class Program { static void Main(string[] args) { Action x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree_ExplicitCast() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action x = (Action)(() => F());/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action x = ... () => F());') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action x = ... (() => F())') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = (Action)(() => F())') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (Action)(() => F())') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: '(Action)(() => F())') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree2() { string source = @" using System; class Program { static void Main(string[] args) { Action x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsVar_HasValidLambdaExpressionTree() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/var x = () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsDelegate_HasValidLambdaExpressionTree() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action<int> x = () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> ... () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> ... = () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsInvalid, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1593: Delegate 'Action<int>' does not take 0 arguments // Action<int> x /*<bind>*/= () => F()/*</bind>*/; Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => F()").WithArguments("System.Action<int>", "0").WithLocation(8, 35) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsDelegate_HasValidLambdaExpressionTree_ExplicitValidCast() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action<int> x = (Action)(() => F());/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> ... () => F());') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> ... (() => F())') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = (Action)(() => F())') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Action)(() => F())') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action<System.Int32>, IsInvalid, IsImplicit) (Syntax: '(Action)(() => F())') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)(() => F())') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'System.Action' to 'System.Action<int>' // /*<bind>*/Action<int> x = (Action)(() => F());/*</bind>*/ Diagnostic(ErrorCode.ERR_NoImplicitConv, "(Action)(() => F())").WithArguments("System.Action", "System.Action<int>").WithLocation(8, 35) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsDelegate_HasValidLambdaExpressionTree_ExplicitInvalidCast() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action<int> x = (Action<int>)(() => F());/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> ... () => F());') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> ... (() => F())') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = (Action ... (() => F())') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Action<i ... (() => F())') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsInvalid) (Syntax: '(Action<int>)(() => F())') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1593: Delegate 'Action<int>' does not take 0 arguments // /*<bind>*/Action<int> x = (Action<int>)(() => F());/*</bind>*/ Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => F()").WithArguments("System.Action<int>", "0").WithLocation(8, 49) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambda_ReferenceEquality() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/var x = () => F();/*</bind>*/ } static void F() { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var syntaxTree = compilation.SyntaxTrees[0]; var semanticModel = compilation.GetSemanticModel(syntaxTree); var variableDeclaration = syntaxTree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var lambdaSyntax = (LambdaExpressionSyntax)variableDeclaration.Declaration.Variables.Single().Initializer.Value; var variableDeclarationGroupOperation = (IVariableDeclarationGroupOperation)semanticModel.GetOperation(variableDeclaration); var variableTreeLambdaOperation = ((IDelegateCreationOperation)variableDeclarationGroupOperation.Declarations.Single().Declarators.Single().Initializer.Value).Target; var lambdaOperation = (IAnonymousFunctionOperation)semanticModel.GetOperation(lambdaSyntax); // Assert that both ways of getting to the lambda (requesting the lambda directly, and requesting via the lambda syntax) // return the same bound node. Assert.Same(variableTreeLambdaOperation, lambdaOperation); var variableDeclarationGroupOperationSecondRequest = (IVariableDeclarationGroupOperation)semanticModel.GetOperation(variableDeclaration); var variableTreeLambdaOperationSecondRequest = ((IDelegateCreationOperation)variableDeclarationGroupOperationSecondRequest.Declarations.Single().Declarators.Single().Initializer.Value).Target; var lambdaOperationSecondRequest = (IAnonymousFunctionOperation)semanticModel.GetOperation(lambdaSyntax); // Assert that, when request the variable declaration or the lambda for a second time, there is no rebinding of the // underlying UnboundLambda, and we get the same IAnonymousFunctionExpression as before Assert.Same(variableTreeLambdaOperation, variableTreeLambdaOperationSecondRequest); Assert.Same(lambdaOperation, lambdaOperationSecondRequest); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_StaticLambda() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action x = static () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action x = ... () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action x = ... c () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = static () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= static () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'static () => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'static () => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,30): error CS8400: Feature 'static anonymous function' is not available in C# 8.0. Please use language version 9.0 or greater. // /*<bind>*/Action x = static () => F();/*</bind>*/ Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "static").WithArguments("static anonymous function", "9.0").WithLocation(8, 30) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>( source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.Regular8 ); var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var syntaxTree = compilation.SyntaxTrees[0]; var semanticModel = compilation.GetSemanticModel(syntaxTree); var variableDeclaration = syntaxTree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var lambdaSyntax = (LambdaExpressionSyntax)variableDeclaration.Declaration.Variables.Single().Initializer.Value; var lambdaOperation = (IAnonymousFunctionOperation)semanticModel.GetOperation(lambdaSyntax); Assert.True(lambdaOperation.Symbol.IsStatic); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_01() { string source = @" struct C { void M(System.Action<bool, bool> d) /*<bind>*/{ d = (bool result, bool input) => { result = input; }; d(false, true); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd = (bool r ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd = (bool r ... }') Left: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean, System.Boolean>, IsImplicit) (Syntax: '(bool resul ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool resul ... }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = input;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = input') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd(false, true);') Expression: IInvocationOperation (virtual void System.Action<System.Boolean, System.Boolean>.Invoke(System.Boolean arg1, System.Boolean arg2)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'd(false, true)') Instance Receiver: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg1) (OperationKind.Argument, Type: null) (Syntax: 'false') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg2) (OperationKind.Argument, Type: null) (Syntax: 'true') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_02() { string source = @" struct C { void M(System.Action<bool, bool> d1, System.Action<bool, bool> d2) /*<bind>*/{ d1 = (bool result1, bool input1) => { result1 = input1; }; d2 = (bool result2, bool input2) => result2 = input2; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd1 = (bool ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd1 = (bool ... }') Left: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd1') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean, System.Boolean>, IsImplicit) (Syntax: '(bool resul ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool resul ... }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result1 = input1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result1 = input1') Left: IParameterReferenceOperation: result1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result1') Right: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input1') Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd2 = (bool ... 2 = input2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd2 = (bool ... t2 = input2') Left: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd2') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean, System.Boolean>, IsImplicit) (Syntax: '(bool resul ... t2 = input2') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool resul ... t2 = input2') { Block[B0#A1] - Entry Statements (0) Next (Regular) Block[B1#A1] Block[B1#A1] - Block Predecessors: [B0#A1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'result2 = input2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result2 = input2') Left: IParameterReferenceOperation: result2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result2') Right: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Next (Regular) Block[B2#A1] Block[B2#A1] - Exit Predecessors: [B1#A1] Statements (0) } Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_03() { string source = @" struct C { void M(System.Action<int> d1, System.Action<bool> d2) /*<bind>*/{ int i = 0; d1 = (int input1) => { input1 = 1; i++; d2 = (bool input2) => { input2 = true; i++; }; }; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd1 = (int i ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Int32>) (Syntax: 'd1 = (int i ... }') Left: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Action<System.Int32>) (Syntax: 'd1') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsImplicit) (Syntax: '(int input1 ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(int input1 ... }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (3) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input1 = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'input1 = 1') Left: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i++;') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd2 = (bool ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean>) (Syntax: 'd2 = (bool ... }') Left: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Action<System.Boolean>) (Syntax: 'd2') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean>, IsImplicit) (Syntax: '(bool input ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool input ... }') { Block[B0#A0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0#A0] Block[B1#A0#A0] - Block Predecessors: [B0#A0#A0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input2 = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'input2 = true') Left: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i++;') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2#A0#A0] Block[B2#A0#A0] - Exit Predecessors: [B1#A0#A0] Statements (0) } Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_04() { string source = @" struct C { void M(System.Action d1, System.Action<bool, bool> d2) /*<bind>*/{ d1 = () => { d2 = (bool result1, bool input1) => { result1 = input1; }; }; void local(bool result2, bool input2) => result2 = input2; }/*</bind>*/ } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var graphM = ControlFlowGraph.Create((IMethodBodyOperation)semanticModel.GetOperation(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); Assert.NotNull(graphM); Assert.Null(graphM.Parent); IFlowAnonymousFunctionOperation lambdaD1 = getLambda(graphM); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraph(lambdaD1.Symbol)); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(lambdaD1.Symbol)); var graphD1 = graphM.GetAnonymousFunctionControlFlowGraph(lambdaD1); Assert.NotNull(graphD1); Assert.Same(graphM, graphD1.Parent); var graphD1_FromExtension = graphM.GetAnonymousFunctionControlFlowGraphInScope(lambdaD1); Assert.Same(graphD1, graphD1_FromExtension); IFlowAnonymousFunctionOperation lambdaD2 = getLambda(graphD1); var graphD2 = graphD1.GetAnonymousFunctionControlFlowGraph(lambdaD2); Assert.NotNull(graphD2); Assert.Same(graphD1, graphD2.Parent); Assert.Throws<ArgumentNullException>(() => graphM.GetAnonymousFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetAnonymousFunctionControlFlowGraph(lambdaD2)); Assert.Throws<ArgumentNullException>(() => graphM.GetAnonymousFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetAnonymousFunctionControlFlowGraphInScope(lambdaD2)); IFlowAnonymousFunctionOperation getLambda(ControlFlowGraph graph) { return graph.Blocks.SelectMany(b => b.Operations.SelectMany(o => o.DescendantsAndSelf())).OfType<IFlowAnonymousFunctionOperation>().Single(); } } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_05() { string source = @" struct C { void M(System.Action d1, System.Action d2) /*<bind>*/{ d1 = () => { }; d2 = () => { d1(); }; }/*</bind>*/ } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var graphM = ControlFlowGraph.Create((IMethodBodyOperation)semanticModel.GetOperation(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); Assert.NotNull(graphM); Assert.Null(graphM.Parent); IFlowAnonymousFunctionOperation lambdaD1 = getLambda(graphM, index: 0); Assert.NotNull(lambdaD1); IFlowAnonymousFunctionOperation lambdaD2 = getLambda(graphM, index: 1); Assert.NotNull(lambdaD2); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraph(lambdaD1.Symbol)); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(lambdaD1.Symbol)); var graphD1 = graphM.GetAnonymousFunctionControlFlowGraph(lambdaD1); Assert.NotNull(graphD1); Assert.Same(graphM, graphD1.Parent); var graphD2 = graphM.GetAnonymousFunctionControlFlowGraph(lambdaD2); Assert.NotNull(graphD2); Assert.Same(graphM, graphD2.Parent); var graphD1_FromExtension = graphM.GetAnonymousFunctionControlFlowGraphInScope(lambdaD1); Assert.Same(graphD1, graphD1_FromExtension); Assert.Throws<ArgumentOutOfRangeException>(() => graphD2.GetAnonymousFunctionControlFlowGraph(lambdaD1)); graphD1_FromExtension = graphD2.GetAnonymousFunctionControlFlowGraphInScope(lambdaD1); Assert.Same(graphD1, graphD1_FromExtension); IFlowAnonymousFunctionOperation getLambda(ControlFlowGraph graph, int index) { return graph.Blocks.SelectMany(b => b.Operations.SelectMany(o => o.DescendantsAndSelf())).OfType<IFlowAnonymousFunctionOperation>().ElementAt(index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IAnonymousFunctionExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action x = () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action x = () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action x = () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree_JustBindingLambdaReturnsOnlyIAnonymousFunctionExpression() { string source = @" using System; class Program { static void Main(string[] args) { Action x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree_ExplicitCast() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action x = (Action)(() => F());/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action x = ... () => F());') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action x = ... (() => F())') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = (Action)(() => F())') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (Action)(() => F())') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: '(Action)(() => F())') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree2() { string source = @" using System; class Program { static void Main(string[] args) { Action x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsVar_HasValidLambdaExpressionTree() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/var x = () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsDelegate_HasValidLambdaExpressionTree() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action<int> x = () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> ... () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> ... = () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsInvalid, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1593: Delegate 'Action<int>' does not take 0 arguments // Action<int> x /*<bind>*/= () => F()/*</bind>*/; Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => F()").WithArguments("System.Action<int>", "0").WithLocation(8, 35) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsDelegate_HasValidLambdaExpressionTree_ExplicitValidCast() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action<int> x = (Action)(() => F());/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> ... () => F());') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> ... (() => F())') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = (Action)(() => F())') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Action)(() => F())') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action<System.Int32>, IsInvalid, IsImplicit) (Syntax: '(Action)(() => F())') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)(() => F())') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'System.Action' to 'System.Action<int>' // /*<bind>*/Action<int> x = (Action)(() => F());/*</bind>*/ Diagnostic(ErrorCode.ERR_NoImplicitConv, "(Action)(() => F())").WithArguments("System.Action", "System.Action<int>").WithLocation(8, 35) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsDelegate_HasValidLambdaExpressionTree_ExplicitInvalidCast() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action<int> x = (Action<int>)(() => F());/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> ... () => F());') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> ... (() => F())') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = (Action ... (() => F())') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Action<i ... (() => F())') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsInvalid) (Syntax: '(Action<int>)(() => F())') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1593: Delegate 'Action<int>' does not take 0 arguments // /*<bind>*/Action<int> x = (Action<int>)(() => F());/*</bind>*/ Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => F()").WithArguments("System.Action<int>", "0").WithLocation(8, 49) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambda_ReferenceEquality() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/var x = () => F();/*</bind>*/ } static void F() { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var syntaxTree = compilation.SyntaxTrees[0]; var semanticModel = compilation.GetSemanticModel(syntaxTree); var variableDeclaration = syntaxTree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var lambdaSyntax = (LambdaExpressionSyntax)variableDeclaration.Declaration.Variables.Single().Initializer.Value; var variableDeclarationGroupOperation = (IVariableDeclarationGroupOperation)semanticModel.GetOperation(variableDeclaration); var variableTreeLambdaOperation = ((IDelegateCreationOperation)variableDeclarationGroupOperation.Declarations.Single().Declarators.Single().Initializer.Value).Target; var lambdaOperation = (IAnonymousFunctionOperation)semanticModel.GetOperation(lambdaSyntax); // Assert that both ways of getting to the lambda (requesting the lambda directly, and requesting via the lambda syntax) // return the same bound node. Assert.Same(variableTreeLambdaOperation, lambdaOperation); var variableDeclarationGroupOperationSecondRequest = (IVariableDeclarationGroupOperation)semanticModel.GetOperation(variableDeclaration); var variableTreeLambdaOperationSecondRequest = ((IDelegateCreationOperation)variableDeclarationGroupOperationSecondRequest.Declarations.Single().Declarators.Single().Initializer.Value).Target; var lambdaOperationSecondRequest = (IAnonymousFunctionOperation)semanticModel.GetOperation(lambdaSyntax); // Assert that, when request the variable declaration or the lambda for a second time, there is no rebinding of the // underlying UnboundLambda, and we get the same IAnonymousFunctionExpression as before Assert.Same(variableTreeLambdaOperation, variableTreeLambdaOperationSecondRequest); Assert.Same(lambdaOperation, lambdaOperationSecondRequest); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_StaticLambda() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action x = static () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action x = ... () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action x = ... c () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = static () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= static () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'static () => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'static () => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,30): error CS8400: Feature 'static anonymous function' is not available in C# 8.0. Please use language version 9.0 or greater. // /*<bind>*/Action x = static () => F();/*</bind>*/ Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "static").WithArguments("static anonymous function", "9.0").WithLocation(8, 30) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>( source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.Regular8 ); var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var syntaxTree = compilation.SyntaxTrees[0]; var semanticModel = compilation.GetSemanticModel(syntaxTree); var variableDeclaration = syntaxTree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var lambdaSyntax = (LambdaExpressionSyntax)variableDeclaration.Declaration.Variables.Single().Initializer.Value; var lambdaOperation = (IAnonymousFunctionOperation)semanticModel.GetOperation(lambdaSyntax); Assert.True(lambdaOperation.Symbol.IsStatic); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_01() { string source = @" struct C { void M(System.Action<bool, bool> d) /*<bind>*/{ d = (bool result, bool input) => { result = input; }; d(false, true); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd = (bool r ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd = (bool r ... }') Left: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean, System.Boolean>, IsImplicit) (Syntax: '(bool resul ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool resul ... }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = input;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = input') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd(false, true);') Expression: IInvocationOperation (virtual void System.Action<System.Boolean, System.Boolean>.Invoke(System.Boolean arg1, System.Boolean arg2)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'd(false, true)') Instance Receiver: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg1) (OperationKind.Argument, Type: null) (Syntax: 'false') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg2) (OperationKind.Argument, Type: null) (Syntax: 'true') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_02() { string source = @" struct C { void M(System.Action<bool, bool> d1, System.Action<bool, bool> d2) /*<bind>*/{ d1 = (bool result1, bool input1) => { result1 = input1; }; d2 = (bool result2, bool input2) => result2 = input2; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd1 = (bool ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd1 = (bool ... }') Left: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd1') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean, System.Boolean>, IsImplicit) (Syntax: '(bool resul ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool resul ... }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result1 = input1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result1 = input1') Left: IParameterReferenceOperation: result1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result1') Right: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input1') Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd2 = (bool ... 2 = input2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd2 = (bool ... t2 = input2') Left: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd2') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean, System.Boolean>, IsImplicit) (Syntax: '(bool resul ... t2 = input2') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool resul ... t2 = input2') { Block[B0#A1] - Entry Statements (0) Next (Regular) Block[B1#A1] Block[B1#A1] - Block Predecessors: [B0#A1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'result2 = input2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result2 = input2') Left: IParameterReferenceOperation: result2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result2') Right: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Next (Regular) Block[B2#A1] Block[B2#A1] - Exit Predecessors: [B1#A1] Statements (0) } Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_03() { string source = @" struct C { void M(System.Action<int> d1, System.Action<bool> d2) /*<bind>*/{ int i = 0; d1 = (int input1) => { input1 = 1; i++; d2 = (bool input2) => { input2 = true; i++; }; }; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd1 = (int i ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Int32>) (Syntax: 'd1 = (int i ... }') Left: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Action<System.Int32>) (Syntax: 'd1') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsImplicit) (Syntax: '(int input1 ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(int input1 ... }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (3) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input1 = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'input1 = 1') Left: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i++;') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd2 = (bool ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean>) (Syntax: 'd2 = (bool ... }') Left: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Action<System.Boolean>) (Syntax: 'd2') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean>, IsImplicit) (Syntax: '(bool input ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool input ... }') { Block[B0#A0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0#A0] Block[B1#A0#A0] - Block Predecessors: [B0#A0#A0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input2 = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'input2 = true') Left: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i++;') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2#A0#A0] Block[B2#A0#A0] - Exit Predecessors: [B1#A0#A0] Statements (0) } Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_04() { string source = @" struct C { void M(System.Action d1, System.Action<bool, bool> d2) /*<bind>*/{ d1 = () => { d2 = (bool result1, bool input1) => { result1 = input1; }; }; void local(bool result2, bool input2) => result2 = input2; }/*</bind>*/ } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var graphM = ControlFlowGraph.Create((IMethodBodyOperation)semanticModel.GetOperation(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); Assert.NotNull(graphM); Assert.Null(graphM.Parent); IFlowAnonymousFunctionOperation lambdaD1 = getLambda(graphM); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraph(lambdaD1.Symbol)); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(lambdaD1.Symbol)); var graphD1 = graphM.GetAnonymousFunctionControlFlowGraph(lambdaD1); Assert.NotNull(graphD1); Assert.Same(graphM, graphD1.Parent); var graphD1_FromExtension = graphM.GetAnonymousFunctionControlFlowGraphInScope(lambdaD1); Assert.Same(graphD1, graphD1_FromExtension); IFlowAnonymousFunctionOperation lambdaD2 = getLambda(graphD1); var graphD2 = graphD1.GetAnonymousFunctionControlFlowGraph(lambdaD2); Assert.NotNull(graphD2); Assert.Same(graphD1, graphD2.Parent); Assert.Throws<ArgumentNullException>(() => graphM.GetAnonymousFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetAnonymousFunctionControlFlowGraph(lambdaD2)); Assert.Throws<ArgumentNullException>(() => graphM.GetAnonymousFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetAnonymousFunctionControlFlowGraphInScope(lambdaD2)); IFlowAnonymousFunctionOperation getLambda(ControlFlowGraph graph) { return graph.Blocks.SelectMany(b => b.Operations.SelectMany(o => o.DescendantsAndSelf())).OfType<IFlowAnonymousFunctionOperation>().Single(); } } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_05() { string source = @" struct C { void M(System.Action d1, System.Action d2) /*<bind>*/{ d1 = () => { }; d2 = () => { d1(); }; }/*</bind>*/ } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var graphM = ControlFlowGraph.Create((IMethodBodyOperation)semanticModel.GetOperation(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); Assert.NotNull(graphM); Assert.Null(graphM.Parent); IFlowAnonymousFunctionOperation lambdaD1 = getLambda(graphM, index: 0); Assert.NotNull(lambdaD1); IFlowAnonymousFunctionOperation lambdaD2 = getLambda(graphM, index: 1); Assert.NotNull(lambdaD2); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraph(lambdaD1.Symbol)); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(lambdaD1.Symbol)); var graphD1 = graphM.GetAnonymousFunctionControlFlowGraph(lambdaD1); Assert.NotNull(graphD1); Assert.Same(graphM, graphD1.Parent); var graphD2 = graphM.GetAnonymousFunctionControlFlowGraph(lambdaD2); Assert.NotNull(graphD2); Assert.Same(graphM, graphD2.Parent); var graphD1_FromExtension = graphM.GetAnonymousFunctionControlFlowGraphInScope(lambdaD1); Assert.Same(graphD1, graphD1_FromExtension); Assert.Throws<ArgumentOutOfRangeException>(() => graphD2.GetAnonymousFunctionControlFlowGraph(lambdaD1)); graphD1_FromExtension = graphD2.GetAnonymousFunctionControlFlowGraphInScope(lambdaD1); Assert.Same(graphD1, graphD1_FromExtension); IFlowAnonymousFunctionOperation getLambda(ControlFlowGraph graph, int index) { return graph.Blocks.SelectMany(b => b.Operations.SelectMany(o => o.DescendantsAndSelf())).OfType<IFlowAnonymousFunctionOperation>().ElementAt(index); } } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/VisualStudio/Core/Test/Progression/ContainsChildrenGraphQueryTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.GraphModel.Schemas Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression <UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)> Public Class ContainsChildrenGraphQueryTests <WpfFact> Public Async Function ContainsChildrenForDocument() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> class C { } </Document> </Project> </Workspace>) Dim inputGraph = testState.GetGraphWithDocumentNode(filePath:="Z:\Project.cs") Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ContainsChildrenGraphQuery(), GraphContextDirection.Self) Dim node = outputContext.Graph.Nodes.Single() AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 @2)" Category="CodeSchema_ProjectItem" ContainsChildren="True" Label="Project.cs"/> </Nodes> <Links/> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/Project.csproj"/> <Alias n="2" Uri="File=file:///Z:/Project.cs"/> </IdentifierAliases> </DirectedGraph>) End Using End Function <WpfFact> Public Async Function ContainsChildrenForEmptyDocument() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> </Document> </Project> </Workspace>) Dim inputGraph = testState.GetGraphWithDocumentNode(filePath:="Z:\Project.cs") Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ContainsChildrenGraphQuery(), GraphContextDirection.Self) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 @2)" Category="CodeSchema_ProjectItem" ContainsChildren="False" Label="Project.cs"/> </Nodes> <Links/> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/Project.csproj"/> <Alias n="2" Uri="File=file:///Z:/Project.cs"/> </IdentifierAliases> </DirectedGraph>) End Using End Function <WorkItem(27805, "https://github.com/dotnet/roslyn/issues/27805")> <WorkItem(233666, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/233666")> <WpfFact> Public Async Function ContainsChildrenForFileWithIllegalPath() As Task Using testState = ProgressionTestState.Create(<Workspace/>) Dim graph = New Graph graph.Nodes.GetOrCreate( GraphNodeId.GetNested(GraphNodeId.GetPartial(CodeGraphNodeIdName.File, New Uri("C:\path\to\""some folder\App.config""", UriKind.RelativeOrAbsolute))), label:=String.Empty, CodeNodeCategories.File) ' Just making sure it doesn't throw. Dim outputContext = Await testState.GetGraphContextAfterQuery(graph, New ContainsChildrenGraphQuery(), GraphContextDirection.Self) End Using End Function <WorkItem(789685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789685")> <WorkItem(794846, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/794846")> <WpfFact> Public Async Function ContainsChildrenForNotYetLoadedSolution() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> class C { } </Document> </Project> </Workspace>) Dim inputGraph = testState.GetGraphWithDocumentNode(filePath:="Z:\Project.cs") ' To simulate the situation where a solution is not yet loaded and project info is not available, ' remove a project from the solution. Dim oldSolution = testState.GetSolution() Dim newSolution = oldSolution.RemoveProject(oldSolution.ProjectIds.FirstOrDefault()) Dim outputContext = Await testState.GetGraphContextAfterQueryWithSolution(inputGraph, newSolution, New ContainsChildrenGraphQuery(), GraphContextDirection.Self) ' ContainsChildren should be set to false, so following updates will be tractable. AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 @2)" Category="CodeSchema_ProjectItem" ContainsChildren="False" Label="Project.cs"/> </Nodes> <Links/> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/Project.csproj"/> <Alias n="2" Uri="File=file:///Z:/Project.cs"/> </IdentifierAliases> </DirectedGraph>) End Using End Function <WorkItem(165369, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/165369")> <WpfFact> Public Async Function ContainsChildrenForNodeWithRelativeUriPath() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj"> <Document FilePath="Z:\Project.vb"> Class C End Class </Document> </Project> </Workspace>) ' Force creation of a graph node that has a nested relative URI file path. This simulates nodes that ' other project types can give us for non-code files. E.g., `favicon.ico` for web projects. Dim nodeId = GraphNodeId.GetNested(GraphNodeId.GetPartial(CodeGraphNodeIdName.File, New Uri("/Z:/Project.vb", UriKind.Relative))) Dim inputGraph = New Graph() Dim node = inputGraph.Nodes.GetOrCreate(nodeId) node.AddCategory(CodeNodeCategories.File) Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ContainsChildrenGraphQuery(), GraphContextDirection.Any) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1)" Category="File" ContainsChildren="False"/> </Nodes> <Links/> <IdentifierAliases> <Alias n="1" Uri="File=/Z:/Project.vb"/> </IdentifierAliases> </DirectedGraph>) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.GraphModel.Schemas Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression <UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)> Public Class ContainsChildrenGraphQueryTests <WpfFact> Public Async Function ContainsChildrenForDocument() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> class C { } </Document> </Project> </Workspace>) Dim inputGraph = testState.GetGraphWithDocumentNode(filePath:="Z:\Project.cs") Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ContainsChildrenGraphQuery(), GraphContextDirection.Self) Dim node = outputContext.Graph.Nodes.Single() AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 @2)" Category="CodeSchema_ProjectItem" ContainsChildren="True" Label="Project.cs"/> </Nodes> <Links/> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/Project.csproj"/> <Alias n="2" Uri="File=file:///Z:/Project.cs"/> </IdentifierAliases> </DirectedGraph>) End Using End Function <WpfFact> Public Async Function ContainsChildrenForEmptyDocument() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> </Document> </Project> </Workspace>) Dim inputGraph = testState.GetGraphWithDocumentNode(filePath:="Z:\Project.cs") Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ContainsChildrenGraphQuery(), GraphContextDirection.Self) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 @2)" Category="CodeSchema_ProjectItem" ContainsChildren="False" Label="Project.cs"/> </Nodes> <Links/> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/Project.csproj"/> <Alias n="2" Uri="File=file:///Z:/Project.cs"/> </IdentifierAliases> </DirectedGraph>) End Using End Function <WorkItem(27805, "https://github.com/dotnet/roslyn/issues/27805")> <WorkItem(233666, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/233666")> <WpfFact> Public Async Function ContainsChildrenForFileWithIllegalPath() As Task Using testState = ProgressionTestState.Create(<Workspace/>) Dim graph = New Graph graph.Nodes.GetOrCreate( GraphNodeId.GetNested(GraphNodeId.GetPartial(CodeGraphNodeIdName.File, New Uri("C:\path\to\""some folder\App.config""", UriKind.RelativeOrAbsolute))), label:=String.Empty, CodeNodeCategories.File) ' Just making sure it doesn't throw. Dim outputContext = Await testState.GetGraphContextAfterQuery(graph, New ContainsChildrenGraphQuery(), GraphContextDirection.Self) End Using End Function <WorkItem(789685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789685")> <WorkItem(794846, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/794846")> <WpfFact> Public Async Function ContainsChildrenForNotYetLoadedSolution() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> class C { } </Document> </Project> </Workspace>) Dim inputGraph = testState.GetGraphWithDocumentNode(filePath:="Z:\Project.cs") ' To simulate the situation where a solution is not yet loaded and project info is not available, ' remove a project from the solution. Dim oldSolution = testState.GetSolution() Dim newSolution = oldSolution.RemoveProject(oldSolution.ProjectIds.FirstOrDefault()) Dim outputContext = Await testState.GetGraphContextAfterQueryWithSolution(inputGraph, newSolution, New ContainsChildrenGraphQuery(), GraphContextDirection.Self) ' ContainsChildren should be set to false, so following updates will be tractable. AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 @2)" Category="CodeSchema_ProjectItem" ContainsChildren="False" Label="Project.cs"/> </Nodes> <Links/> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/Project.csproj"/> <Alias n="2" Uri="File=file:///Z:/Project.cs"/> </IdentifierAliases> </DirectedGraph>) End Using End Function <WorkItem(165369, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/165369")> <WpfFact> Public Async Function ContainsChildrenForNodeWithRelativeUriPath() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj"> <Document FilePath="Z:\Project.vb"> Class C End Class </Document> </Project> </Workspace>) ' Force creation of a graph node that has a nested relative URI file path. This simulates nodes that ' other project types can give us for non-code files. E.g., `favicon.ico` for web projects. Dim nodeId = GraphNodeId.GetNested(GraphNodeId.GetPartial(CodeGraphNodeIdName.File, New Uri("/Z:/Project.vb", UriKind.Relative))) Dim inputGraph = New Graph() Dim node = inputGraph.Nodes.GetOrCreate(nodeId) node.AddCategory(CodeNodeCategories.File) Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ContainsChildrenGraphQuery(), GraphContextDirection.Any) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1)" Category="File" ContainsChildren="False"/> </Nodes> <Links/> <IdentifierAliases> <Alias n="1" Uri="File=/Z:/Project.vb"/> </IdentifierAliases> </DirectedGraph>) End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/VisualStudio/Xaml/Impl/CodeFixes/RemoveUnnecessaryUsings/XamlRemoveUnnecessaryUsingsCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editor.Xaml.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.RemoveUnnecessaryImports; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Xaml; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Xaml.CodeFixes.RemoveUnusedUsings { [ExportCodeFixProvider(StringConstants.XamlLanguageName, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryImports), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.AddMissingReference)] internal class RemoveUnnecessaryUsingsCodeFixProvider : CodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoveUnnecessaryUsingsCodeFixProvider() { } public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(XamlDiagnosticIds.UnnecessaryNamespacesId); } } public override FixAllProvider GetFixAllProvider() { // Fix All is not supported by this code fix, because the action already applies to one document at a time return null; } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction( c => RemoveUnnecessaryImportsAsync(context.Document, c)), context.Diagnostics); return Task.CompletedTask; } private Task<Document> RemoveUnnecessaryImportsAsync( Document document, CancellationToken cancellationToken) { var service = document.GetLanguageService<IRemoveUnnecessaryImportsService>(); return service.RemoveUnnecessaryImportsAsync(document, cancellationToken); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(Resources.RemoveUnnecessaryNamespaces, createChangedDocument, nameof(Resources.RemoveUnnecessaryNamespaces)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editor.Xaml.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.RemoveUnnecessaryImports; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Xaml; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Xaml.CodeFixes.RemoveUnusedUsings { [ExportCodeFixProvider(StringConstants.XamlLanguageName, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryImports), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.AddMissingReference)] internal class RemoveUnnecessaryUsingsCodeFixProvider : CodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoveUnnecessaryUsingsCodeFixProvider() { } public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(XamlDiagnosticIds.UnnecessaryNamespacesId); } } public override FixAllProvider GetFixAllProvider() { // Fix All is not supported by this code fix, because the action already applies to one document at a time return null; } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction( c => RemoveUnnecessaryImportsAsync(context.Document, c)), context.Diagnostics); return Task.CompletedTask; } private Task<Document> RemoveUnnecessaryImportsAsync( Document document, CancellationToken cancellationToken) { var service = document.GetLanguageService<IRemoveUnnecessaryImportsService>(); return service.RemoveUnnecessaryImportsAsync(document, cancellationToken); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(Resources.RemoveUnnecessaryNamespaces, createChangedDocument, nameof(Resources.RemoveUnnecessaryNamespaces)) { } } } }
-1
dotnet/roslyn
55,441
Support SwitchExpression in SmartBreakline
Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
Cosifne
2021-08-05T19:39:23Z
2021-09-27T22:32:26Z
9ec2b398d5bad712570440c3bb48590525e5de83
ed0689307727781692f8e069cff4e1fdd801a79b
Support SwitchExpression in SmartBreakline. Fix https://github.com/dotnet/roslyn/issues/54387 Support add braces pairs for SwitchExpression
./src/Features/VisualBasic/Portable/Structure/Providers/ObjectCreationInitializerStructureProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class ObjectCreationInitializerStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of ObjectCreationInitializerSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As ObjectCreationInitializerSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) ' ObjectCreationInitializerSyntax is either "With { ... }" or "From { ... }" ' Parent Is something Like ' ' New Dictionary(Of int, string) From { ' ... ' } ' ' The collapsed textspan should be from the ) to the } ' ' However, the hint span should be the entire object creation. spans.Add(New BlockSpan( isCollapsible:=True, textSpan:=TextSpan.FromBounds(previousToken.Span.End, node.Span.End), hintSpan:=node.Parent.Span, type:=BlockTypes.Expression)) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class ObjectCreationInitializerStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of ObjectCreationInitializerSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As ObjectCreationInitializerSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) ' ObjectCreationInitializerSyntax is either "With { ... }" or "From { ... }" ' Parent Is something Like ' ' New Dictionary(Of int, string) From { ' ... ' } ' ' The collapsed textspan should be from the ) to the } ' ' However, the hint span should be the entire object creation. spans.Add(New BlockSpan( isCollapsible:=True, textSpan:=TextSpan.FromBounds(previousToken.Span.End, node.Span.End), hintSpan:=node.Parent.Span, type:=BlockTypes.Expression)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/Version.Details.xml
<?xml version="1.0" encoding="utf-8"?> <Dependencies> <ProductDependencies> <Dependency Name="XliffTasks" Version="1.0.0-beta.21215.1"> <Uri>https://github.com/dotnet/xliff-tasks</Uri> <Sha>7e80445ee82adbf9a8e6ae601ac5e239d982afaa</Sha> <SourceBuild RepoName="xliff-tasks" ManagedOnly="true" /> </Dependency> <Dependency Name="Microsoft.SourceBuild.Intermediate.source-build" Version="0.1.0-alpha.1.21452.1"> <Uri>https://github.com/dotnet/source-build</Uri> <Sha>a9515db097e05728fcc2169d074eae3c6a4580d0</Sha> <SourceBuild RepoName="source-build" ManagedOnly="true" /> </Dependency> </ProductDependencies> <ToolsetDependencies> <Dependency Name="Microsoft.DotNet.Arcade.Sdk" Version="6.0.0-beta.21413.4"> <Uri>https://github.com/dotnet/arcade</Uri> <Sha>9b7027ba718462aa6410cef61a8be5a4283e7528</Sha> <SourceBuild RepoName="arcade" ManagedOnly="true" /> </Dependency> <Dependency Name="Microsoft.Net.Compilers.Toolset" Version="4.0.0-4.21420.19"> <Uri>https://github.com/dotnet/roslyn</Uri> <Sha>158f906df6b1e4ca99fe7cf6ed78822515d64230</Sha> </Dependency> <Dependency Name="Microsoft.DotNet.Helix.Sdk" Version="6.0.0-beta.21413.4"> <Uri>https://github.com/dotnet/arcade</Uri> <Sha>9b7027ba718462aa6410cef61a8be5a4283e7528</Sha> </Dependency> </ToolsetDependencies> </Dependencies>
<?xml version="1.0" encoding="utf-8"?> <Dependencies> <ProductDependencies> <Dependency Name="XliffTasks" Version="1.0.0-beta.21215.1"> <Uri>https://github.com/dotnet/xliff-tasks</Uri> <Sha>7e80445ee82adbf9a8e6ae601ac5e239d982afaa</Sha> <SourceBuild RepoName="xliff-tasks" ManagedOnly="true" /> </Dependency> <Dependency Name="Microsoft.SourceBuild.Intermediate.source-build" Version="0.1.0-alpha.1.21452.1"> <Uri>https://github.com/dotnet/source-build</Uri> <Sha>a9515db097e05728fcc2169d074eae3c6a4580d0</Sha> <SourceBuild RepoName="source-build" ManagedOnly="true" /> </Dependency> </ProductDependencies> <ToolsetDependencies> <Dependency Name="Microsoft.DotNet.Arcade.Sdk" Version="7.0.0-beta.21463.4"> <Uri>https://github.com/dotnet/arcade</Uri> <Sha>4b7c80f398fd3dcea03fdc4e454789b61181d300</Sha> <SourceBuild RepoName="arcade" ManagedOnly="true" /> </Dependency> <Dependency Name="Microsoft.Net.Compilers.Toolset" Version="4.0.0-4.21420.19"> <Uri>https://github.com/dotnet/roslyn</Uri> <Sha>158f906df6b1e4ca99fe7cf6ed78822515d64230</Sha> </Dependency> <Dependency Name="Microsoft.DotNet.Helix.Sdk" Version="7.0.0-beta.21463.4"> <Uri>https://github.com/dotnet/arcade</Uri> <Sha>4b7c80f398fd3dcea03fdc4e454789b61181d300</Sha> </Dependency> </ToolsetDependencies> </Dependencies>
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/build.sh
#!/usr/bin/env bash # Stop script if unbound variable found (use ${var:-} if intentional) set -u # Stop script if command returns non-zero exit code. # Prevents hidden errors caused by missing error code propagation. set -e usage() { echo "Common settings:" echo " --configuration <value> Build configuration: 'Debug' or 'Release' (short: -c)" echo " --verbosity <value> Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic] (short: -v)" echo " --binaryLog Create MSBuild binary log (short: -bl)" echo " --help Print help and exit (short: -h)" echo "" echo "Actions:" echo " --restore Restore dependencies (short: -r)" echo " --build Build solution (short: -b)" echo " --rebuild Rebuild solution" echo " --test Run all unit tests in the solution (short: -t)" echo " --integrationTest Run all integration tests in the solution" echo " --performanceTest Run all performance tests in the solution" echo " --pack Package build outputs into NuGet packages and Willow components" echo " --sign Sign build outputs" echo " --publish Publish artifacts (e.g. symbols)" echo " --clean Clean the solution" echo "" echo "Advanced settings:" echo " --projects <value> Project or solution file(s) to build" echo " --ci Set when running on CI server" echo " --excludeCIBinarylog Don't output binary log (short: -nobl)" echo " --prepareMachine Prepare machine for CI run, clean up processes after build" echo " --nodeReuse <value> Sets nodereuse msbuild parameter ('true' or 'false')" echo " --warnAsError <value> Sets warnaserror msbuild parameter ('true' or 'false')" echo "" echo "Command line arguments not listed above are passed thru to msbuild." echo "Arguments can also be passed in with a single hyphen." } source="${BASH_SOURCE[0]}" # resolve $source until the file is no longer a symlink while [[ -h "$source" ]]; do scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" source="$(readlink "$source")" # if $source was a relative symlink, we need to resolve it relative to the path where the # symlink file was located [[ $source != /* ]] && source="$scriptroot/$source" done scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" restore=false build=false rebuild=false test=false integration_test=false performance_test=false pack=false publish=false sign=false public=false ci=false clean=false warn_as_error=true node_reuse=true binary_log=false exclude_ci_binary_log=false pipelines_log=false projects='' configuration='Debug' prepare_machine=false verbosity='minimal' runtime_source_feed='' runtime_source_feed_key='' properties='' while [[ $# > 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -help|-h) usage exit 0 ;; -clean) clean=true ;; -configuration|-c) configuration=$2 shift ;; -verbosity|-v) verbosity=$2 shift ;; -binarylog|-bl) binary_log=true ;; -excludeCIBinarylog|-nobl) exclude_ci_binary_log=true ;; -pipelineslog|-pl) pipelines_log=true ;; -restore|-r) restore=true ;; -build|-b) build=true ;; -rebuild) rebuild=true ;; -pack) pack=true ;; -test|-t) test=true ;; -integrationtest) integration_test=true ;; -performancetest) performance_test=true ;; -sign) sign=true ;; -publish) publish=true ;; -preparemachine) prepare_machine=true ;; -projects) projects=$2 shift ;; -ci) ci=true ;; -warnaserror) warn_as_error=$2 shift ;; -nodereuse) node_reuse=$2 shift ;; -runtimesourcefeed) runtime_source_feed=$2 shift ;; -runtimesourcefeedkey) runtime_source_feed_key=$2 shift ;; *) properties="$properties $1" ;; esac shift done if [[ "$ci" == true ]]; then pipelines_log=true node_reuse=false if [[ "$exclude_ci_binary_log" == false ]]; then binary_log=true fi fi . "$scriptroot/tools.sh" function InitializeCustomToolset { local script="$eng_root/restore-toolset.sh" if [[ -a "$script" ]]; then . "$script" fi } function Build { InitializeToolset InitializeCustomToolset if [[ ! -z "$projects" ]]; then properties="$properties /p:Projects=$projects" fi local bl="" if [[ "$binary_log" == true ]]; then bl="/bl:\"$log_dir/Build.binlog\"" fi MSBuild $_InitializeToolset \ $bl \ /p:Configuration=$configuration \ /p:RepoRoot="$repo_root" \ /p:Restore=$restore \ /p:Build=$build \ /p:Rebuild=$rebuild \ /p:Test=$test \ /p:Pack=$pack \ /p:IntegrationTest=$integration_test \ /p:PerformanceTest=$performance_test \ /p:Sign=$sign \ /p:Publish=$publish \ $properties ExitWithExitCode 0 } if [[ "$clean" == true ]]; then if [ -d "$artifacts_dir" ]; then rm -rf $artifacts_dir echo "Artifacts directory deleted." fi exit 0 fi if [[ "$restore" == true ]]; then InitializeNativeTools fi Build
#!/usr/bin/env bash # Stop script if unbound variable found (use ${var:-} if intentional) set -u # Stop script if command returns non-zero exit code. # Prevents hidden errors caused by missing error code propagation. set -e usage() { echo "Common settings:" echo " --configuration <value> Build configuration: 'Debug' or 'Release' (short: -c)" echo " --verbosity <value> Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic] (short: -v)" echo " --binaryLog Create MSBuild binary log (short: -bl)" echo " --help Print help and exit (short: -h)" echo "" echo "Actions:" echo " --restore Restore dependencies (short: -r)" echo " --build Build solution (short: -b)" echo " --rebuild Rebuild solution" echo " --test Run all unit tests in the solution (short: -t)" echo " --integrationTest Run all integration tests in the solution" echo " --performanceTest Run all performance tests in the solution" echo " --pack Package build outputs into NuGet packages and Willow components" echo " --sign Sign build outputs" echo " --publish Publish artifacts (e.g. symbols)" echo " --clean Clean the solution" echo "" echo "Advanced settings:" echo " --projects <value> Project or solution file(s) to build" echo " --ci Set when running on CI server" echo " --excludeCIBinarylog Don't output binary log (short: -nobl)" echo " --prepareMachine Prepare machine for CI run, clean up processes after build" echo " --nodeReuse <value> Sets nodereuse msbuild parameter ('true' or 'false')" echo " --warnAsError <value> Sets warnaserror msbuild parameter ('true' or 'false')" echo "" echo "Command line arguments not listed above are passed thru to msbuild." echo "Arguments can also be passed in with a single hyphen." } source="${BASH_SOURCE[0]}" # resolve $source until the file is no longer a symlink while [[ -h "$source" ]]; do scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" source="$(readlink "$source")" # if $source was a relative symlink, we need to resolve it relative to the path where the # symlink file was located [[ $source != /* ]] && source="$scriptroot/$source" done scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" restore=false build=false rebuild=false test=false integration_test=false performance_test=false pack=false publish=false sign=false public=false ci=false clean=false warn_as_error=true node_reuse=true binary_log=false exclude_ci_binary_log=false pipelines_log=false projects='' configuration='Debug' prepare_machine=false verbosity='minimal' runtime_source_feed='' runtime_source_feed_key='' properties='' while [[ $# > 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -help|-h) usage exit 0 ;; -clean) clean=true ;; -configuration|-c) configuration=$2 shift ;; -verbosity|-v) verbosity=$2 shift ;; -binarylog|-bl) binary_log=true ;; -excludeCIBinarylog|-nobl) exclude_ci_binary_log=true ;; -pipelineslog|-pl) pipelines_log=true ;; -restore|-r) restore=true ;; -build|-b) build=true ;; -rebuild) rebuild=true ;; -pack) pack=true ;; -test|-t) test=true ;; -integrationtest) integration_test=true ;; -performancetest) performance_test=true ;; -sign) sign=true ;; -publish) publish=true ;; -preparemachine) prepare_machine=true ;; -projects) projects=$2 shift ;; -ci) ci=true ;; -warnaserror) warn_as_error=$2 shift ;; -nodereuse) node_reuse=$2 shift ;; -runtimesourcefeed) runtime_source_feed=$2 shift ;; -runtimesourcefeedkey) runtime_source_feed_key=$2 shift ;; *) properties="$properties $1" ;; esac shift done if [[ "$ci" == true ]]; then pipelines_log=true node_reuse=false if [[ "$exclude_ci_binary_log" == false ]]; then binary_log=true fi fi . "$scriptroot/tools.sh" function InitializeCustomToolset { local script="$eng_root/restore-toolset.sh" if [[ -a "$script" ]]; then . "$script" fi } function Build { if [[ "$ci" == true ]]; then TryLogClientIpAddress fi InitializeToolset InitializeCustomToolset if [[ ! -z "$projects" ]]; then properties="$properties /p:Projects=$projects" fi local bl="" if [[ "$binary_log" == true ]]; then bl="/bl:\"$log_dir/Build.binlog\"" fi MSBuild $_InitializeToolset \ $bl \ /p:Configuration=$configuration \ /p:RepoRoot="$repo_root" \ /p:Restore=$restore \ /p:Build=$build \ /p:Rebuild=$rebuild \ /p:Test=$test \ /p:Pack=$pack \ /p:IntegrationTest=$integration_test \ /p:PerformanceTest=$performance_test \ /p:Sign=$sign \ /p:Publish=$publish \ $properties ExitWithExitCode 0 } if [[ "$clean" == true ]]; then if [ -d "$artifacts_dir" ]; then rm -rf $artifacts_dir echo "Artifacts directory deleted." fi exit 0 fi if [[ "$restore" == true ]]; then InitializeNativeTools fi Build
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/cross/build-rootfs.sh
#!/usr/bin/env bash set -e usage() { echo "Usage: $0 [BuildArch] [CodeName] [lldbx.y] [--skipunmount] --rootfsdir <directory>]" echo "BuildArch can be: arm(default), armel, arm64, x86" echo "CodeName - optional, Code name for Linux, can be: xenial(default), zesty, bionic, alpine, alpine3.9 or alpine3.13. If BuildArch is armel, LinuxCodeName is jessie(default) or tizen." echo " for FreeBSD can be: freebsd11, freebsd12, freebsd13" echo " for illumos can be: illumos." echo "lldbx.y - optional, LLDB version, can be: lldb3.9(default), lldb4.0, lldb5.0, lldb6.0 no-lldb. Ignored for alpine and FreeBSD" echo "--skipunmount - optional, will skip the unmount of rootfs folder." echo "--use-mirror - optional, use mirror URL to fetch resources, when available." exit 1 } __CodeName=xenial __CrossDir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) __InitialDir=$PWD __BuildArch=arm __AlpineArch=armv7 __QEMUArch=arm __UbuntuArch=armhf __UbuntuRepo="http://ports.ubuntu.com/" __LLDB_Package="liblldb-3.9-dev" __SkipUnmount=0 # base development support __UbuntuPackages="build-essential" __AlpinePackages="alpine-base" __AlpinePackages+=" build-base" __AlpinePackages+=" linux-headers" __AlpinePackagesEdgeCommunity=" lldb-dev" __AlpinePackagesEdgeMain+=" python3" __AlpinePackagesEdgeMain+=" libedit" # symlinks fixer __UbuntuPackages+=" symlinks" # CoreCLR and CoreFX dependencies __UbuntuPackages+=" libicu-dev" __UbuntuPackages+=" liblttng-ust-dev" __UbuntuPackages+=" libunwind8-dev" __AlpinePackages+=" gettext-dev" __AlpinePackages+=" icu-dev" __AlpinePackages+=" libunwind-dev" __AlpinePackages+=" lttng-ust-dev" # CoreFX dependencies __UbuntuPackages+=" libcurl4-openssl-dev" __UbuntuPackages+=" libkrb5-dev" __UbuntuPackages+=" libssl-dev" __UbuntuPackages+=" zlib1g-dev" __AlpinePackages+=" curl-dev" __AlpinePackages+=" krb5-dev" __AlpinePackages+=" openssl-dev" __AlpinePackages+=" zlib-dev" __FreeBSDBase="12.2-RELEASE" __FreeBSDPkg="1.12.0" __FreeBSDABI="12" __FreeBSDPackages="libunwind" __FreeBSDPackages+=" icu" __FreeBSDPackages+=" libinotify" __FreeBSDPackages+=" lttng-ust" __FreeBSDPackages+=" krb5" __FreeBSDPackages+=" terminfo-db" __IllumosPackages="icu-64.2nb2" __IllumosPackages+=" mit-krb5-1.16.2nb4" __IllumosPackages+=" openssl-1.1.1e" __IllumosPackages+=" zlib-1.2.11" # ML.NET dependencies __UbuntuPackages+=" libomp5" __UbuntuPackages+=" libomp-dev" __UseMirror=0 __UnprocessedBuildArgs= while :; do if [ $# -le 0 ]; then break fi lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" case $lowerI in -?|-h|--help) usage exit 1 ;; arm) __BuildArch=arm __UbuntuArch=armhf __AlpineArch=armv7 __QEMUArch=arm ;; arm64) __BuildArch=arm64 __UbuntuArch=arm64 __AlpineArch=aarch64 __QEMUArch=aarch64 ;; armel) __BuildArch=armel __UbuntuArch=armel __UbuntuRepo="http://ftp.debian.org/debian/" __CodeName=jessie ;; s390x) __BuildArch=s390x __UbuntuArch=s390x __UbuntuRepo="http://ports.ubuntu.com/ubuntu-ports/" __UbuntuPackages=$(echo ${__UbuntuPackages} | sed 's/ libunwind8-dev//') __UbuntuPackages=$(echo ${__UbuntuPackages} | sed 's/ libomp-dev//') __UbuntuPackages=$(echo ${__UbuntuPackages} | sed 's/ libomp5//') unset __LLDB_Package ;; x86) __BuildArch=x86 __UbuntuArch=i386 __UbuntuRepo="http://archive.ubuntu.com/ubuntu/" ;; lldb3.6) __LLDB_Package="lldb-3.6-dev" ;; lldb3.8) __LLDB_Package="lldb-3.8-dev" ;; lldb3.9) __LLDB_Package="liblldb-3.9-dev" ;; lldb4.0) __LLDB_Package="liblldb-4.0-dev" ;; lldb5.0) __LLDB_Package="liblldb-5.0-dev" ;; lldb6.0) __LLDB_Package="liblldb-6.0-dev" ;; no-lldb) unset __LLDB_Package ;; xenial) # Ubuntu 16.04 if [ "$__CodeName" != "jessie" ]; then __CodeName=xenial fi ;; zesty) # Ubuntu 17.04 if [ "$__CodeName" != "jessie" ]; then __CodeName=zesty fi ;; bionic) # Ubuntu 18.04 if [ "$__CodeName" != "jessie" ]; then __CodeName=bionic fi ;; jessie) # Debian 8 __CodeName=jessie __UbuntuRepo="http://ftp.debian.org/debian/" ;; stretch) # Debian 9 __CodeName=stretch __UbuntuRepo="http://ftp.debian.org/debian/" __LLDB_Package="liblldb-6.0-dev" ;; buster) # Debian 10 __CodeName=buster __UbuntuRepo="http://ftp.debian.org/debian/" __LLDB_Package="liblldb-6.0-dev" ;; tizen) if [ "$__BuildArch" != "armel" ] && [ "$__BuildArch" != "arm64" ]; then echo "Tizen is available only for armel and arm64." usage; exit 1; fi __CodeName= __UbuntuRepo= __Tizen=tizen ;; alpine|alpine3.9) __CodeName=alpine __UbuntuRepo= __AlpineVersion=3.9 __AlpinePackagesEdgeMain+=" llvm11-libs" __AlpinePackagesEdgeMain+=" clang-libs" ;; alpine3.13) __CodeName=alpine __UbuntuRepo= __AlpineVersion=3.13 # Alpine 3.13 has all the packages we need in the 3.13 repository __AlpinePackages+=$__AlpinePackagesEdgeCommunity __AlpinePackagesEdgeCommunity= __AlpinePackages+=$__AlpinePackagesEdgeMain __AlpinePackagesEdgeMain= __AlpinePackages+=" llvm10-libs" ;; freebsd11) __FreeBSDBase="11.3-RELEASE" __FreeBSDABI="11" ;& freebsd12) __CodeName=freebsd __BuildArch=x64 __SkipUnmount=1 ;; freebsd13) __CodeName=freebsd __FreeBSDBase="13.0-RELEASE" __FreeBSDABI="13" __BuildArch=x64 __SkipUnmount=1 ;; illumos) __CodeName=illumos __BuildArch=x64 __SkipUnmount=1 ;; --skipunmount) __SkipUnmount=1 ;; --rootfsdir|-rootfsdir) shift __RootfsDir=$1 ;; --use-mirror) __UseMirror=1 ;; *) __UnprocessedBuildArgs="$__UnprocessedBuildArgs $1" ;; esac shift done if [ "$__BuildArch" == "armel" ]; then __LLDB_Package="lldb-3.5-dev" fi __UbuntuPackages+=" ${__LLDB_Package:-}" if [ -z "$__RootfsDir" ] && [ ! -z "$ROOTFS_DIR" ]; then __RootfsDir=$ROOTFS_DIR fi if [ -z "$__RootfsDir" ]; then __RootfsDir="$__CrossDir/../../../.tools/rootfs/$__BuildArch" fi if [ -d "$__RootfsDir" ]; then if [ $__SkipUnmount == 0 ]; then umount $__RootfsDir/* || true fi rm -rf $__RootfsDir fi mkdir -p $__RootfsDir __RootfsDir="$( cd "$__RootfsDir" && pwd )" if [[ "$__CodeName" == "alpine" ]]; then __ApkToolsVersion=2.9.1 __ApkToolsDir=$(mktemp -d) wget https://github.com/alpinelinux/apk-tools/releases/download/v$__ApkToolsVersion/apk-tools-$__ApkToolsVersion-x86_64-linux.tar.gz -P $__ApkToolsDir tar -xf $__ApkToolsDir/apk-tools-$__ApkToolsVersion-x86_64-linux.tar.gz -C $__ApkToolsDir mkdir -p $__RootfsDir/usr/bin cp -v /usr/bin/qemu-$__QEMUArch-static $__RootfsDir/usr/bin $__ApkToolsDir/apk-tools-$__ApkToolsVersion/apk \ -X http://dl-cdn.alpinelinux.org/alpine/v$__AlpineVersion/main \ -X http://dl-cdn.alpinelinux.org/alpine/v$__AlpineVersion/community \ -U --allow-untrusted --root $__RootfsDir --arch $__AlpineArch --initdb \ add $__AlpinePackages if [[ -n "$__AlpinePackagesEdgeMain" ]]; then $__ApkToolsDir/apk-tools-$__ApkToolsVersion/apk \ -X http://dl-cdn.alpinelinux.org/alpine/edge/main \ -U --allow-untrusted --root $__RootfsDir --arch $__AlpineArch --initdb \ add $__AlpinePackagesEdgeMain fi if [[ -n "$__AlpinePackagesEdgeCommunity" ]]; then $__ApkToolsDir/apk-tools-$__ApkToolsVersion/apk \ -X http://dl-cdn.alpinelinux.org/alpine/edge/community \ -U --allow-untrusted --root $__RootfsDir --arch $__AlpineArch --initdb \ add $__AlpinePackagesEdgeCommunity fi rm -r $__ApkToolsDir elif [[ "$__CodeName" == "freebsd" ]]; then mkdir -p $__RootfsDir/usr/local/etc JOBS="$(getconf _NPROCESSORS_ONLN)" wget -O - https://download.freebsd.org/ftp/releases/amd64/${__FreeBSDBase}/base.txz | tar -C $__RootfsDir -Jxf - ./lib ./usr/lib ./usr/libdata ./usr/include ./usr/share/keys ./etc ./bin/freebsd-version echo "ABI = \"FreeBSD:${__FreeBSDABI}:amd64\"; FINGERPRINTS = \"${__RootfsDir}/usr/share/keys\"; REPOS_DIR = [\"${__RootfsDir}/etc/pkg\"]; REPO_AUTOUPDATE = NO; RUN_SCRIPTS = NO;" > ${__RootfsDir}/usr/local/etc/pkg.conf echo "FreeBSD: { url: "pkg+http://pkg.FreeBSD.org/\${ABI}/quarterly", mirror_type: \"srv\", signature_type: \"fingerprints\", fingerprints: \"${__RootfsDir}/usr/share/keys/pkg\", enabled: yes }" > ${__RootfsDir}/etc/pkg/FreeBSD.conf mkdir -p $__RootfsDir/tmp # get and build package manager wget -O - https://github.com/freebsd/pkg/archive/${__FreeBSDPkg}.tar.gz | tar -C $__RootfsDir/tmp -zxf - cd $__RootfsDir/tmp/pkg-${__FreeBSDPkg} # needed for install to succeed mkdir -p $__RootfsDir/host/etc ./autogen.sh && ./configure --prefix=$__RootfsDir/host && make -j "$JOBS" && make install rm -rf $__RootfsDir/tmp/pkg-${__FreeBSDPkg} # install packages we need. INSTALL_AS_USER=$(whoami) $__RootfsDir/host/sbin/pkg -r $__RootfsDir -C $__RootfsDir/usr/local/etc/pkg.conf update INSTALL_AS_USER=$(whoami) $__RootfsDir/host/sbin/pkg -r $__RootfsDir -C $__RootfsDir/usr/local/etc/pkg.conf install --yes $__FreeBSDPackages elif [[ "$__CodeName" == "illumos" ]]; then mkdir "$__RootfsDir/tmp" pushd "$__RootfsDir/tmp" JOBS="$(getconf _NPROCESSORS_ONLN)" echo "Downloading sysroot." wget -O - https://github.com/illumos/sysroot/releases/download/20181213-de6af22ae73b-v1/illumos-sysroot-i386-20181213-de6af22ae73b-v1.tar.gz | tar -C "$__RootfsDir" -xzf - echo "Building binutils. Please wait.." wget -O - https://ftp.gnu.org/gnu/binutils/binutils-2.33.1.tar.bz2 | tar -xjf - mkdir build-binutils && cd build-binutils ../binutils-2.33.1/configure --prefix="$__RootfsDir" --target="x86_64-sun-solaris2.10" --program-prefix="x86_64-illumos-" --with-sysroot="$__RootfsDir" make -j "$JOBS" && make install && cd .. echo "Building gcc. Please wait.." wget -O - https://ftp.gnu.org/gnu/gcc/gcc-8.4.0/gcc-8.4.0.tar.xz | tar -xJf - CFLAGS="-fPIC" CXXFLAGS="-fPIC" CXXFLAGS_FOR_TARGET="-fPIC" CFLAGS_FOR_TARGET="-fPIC" export CFLAGS CXXFLAGS CXXFLAGS_FOR_TARGET CFLAGS_FOR_TARGET mkdir build-gcc && cd build-gcc ../gcc-8.4.0/configure --prefix="$__RootfsDir" --target="x86_64-sun-solaris2.10" --program-prefix="x86_64-illumos-" --with-sysroot="$__RootfsDir" --with-gnu-as \ --with-gnu-ld --disable-nls --disable-libgomp --disable-libquadmath --disable-libssp --disable-libvtv --disable-libcilkrts --disable-libada --disable-libsanitizer \ --disable-libquadmath-support --disable-shared --enable-tls make -j "$JOBS" && make install && cd .. BaseUrl=https://pkgsrc.joyent.com if [[ "$__UseMirror" == 1 ]]; then BaseUrl=http://pkgsrc.smartos.skylime.net fi BaseUrl="$BaseUrl"/packages/SmartOS/2020Q1/x86_64/All echo "Downloading dependencies." read -ra array <<<"$__IllumosPackages" for package in "${array[@]}"; do echo "Installing $package..." wget "$BaseUrl"/"$package".tgz ar -x "$package".tgz tar --skip-old-files -xzf "$package".tmp.tgz -C "$__RootfsDir" 2>/dev/null done echo "Cleaning up temporary files." popd rm -rf "$__RootfsDir"/{tmp,+*} mkdir -p "$__RootfsDir"/usr/include/net mkdir -p "$__RootfsDir"/usr/include/netpacket wget -P "$__RootfsDir"/usr/include/net https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/io/bpf/net/bpf.h wget -P "$__RootfsDir"/usr/include/net https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/io/bpf/net/dlt.h wget -P "$__RootfsDir"/usr/include/netpacket https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/inet/sockmods/netpacket/packet.h wget -P "$__RootfsDir"/usr/include/sys https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/sys/sdt.h elif [[ -n $__CodeName ]]; then qemu-debootstrap --arch $__UbuntuArch $__CodeName $__RootfsDir $__UbuntuRepo cp $__CrossDir/$__BuildArch/sources.list.$__CodeName $__RootfsDir/etc/apt/sources.list chroot $__RootfsDir apt-get update chroot $__RootfsDir apt-get -f -y install chroot $__RootfsDir apt-get -y install $__UbuntuPackages chroot $__RootfsDir symlinks -cr /usr chroot $__RootfsDir apt-get clean if [ $__SkipUnmount == 0 ]; then umount $__RootfsDir/* || true fi if [[ "$__BuildArch" == "armel" && "$__CodeName" == "jessie" ]]; then pushd $__RootfsDir patch -p1 < $__CrossDir/$__BuildArch/armel.jessie.patch popd fi elif [[ "$__Tizen" == "tizen" ]]; then ROOTFS_DIR=$__RootfsDir $__CrossDir/$__BuildArch/tizen-build-rootfs.sh else echo "Unsupported target platform." usage; exit 1 fi
#!/usr/bin/env bash set -e usage() { echo "Usage: $0 [BuildArch] [CodeName] [lldbx.y] [--skipunmount] --rootfsdir <directory>]" echo "BuildArch can be: arm(default), armel, arm64, x86" echo "CodeName - optional, Code name for Linux, can be: xenial(default), zesty, bionic, alpine, alpine3.13 or alpine3.14. If BuildArch is armel, LinuxCodeName is jessie(default) or tizen." echo " for FreeBSD can be: freebsd11, freebsd12, freebsd13" echo " for illumos can be: illumos." echo "lldbx.y - optional, LLDB version, can be: lldb3.9(default), lldb4.0, lldb5.0, lldb6.0 no-lldb. Ignored for alpine and FreeBSD" echo "--skipunmount - optional, will skip the unmount of rootfs folder." echo "--use-mirror - optional, use mirror URL to fetch resources, when available." exit 1 } __CodeName=xenial __CrossDir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) __InitialDir=$PWD __BuildArch=arm __AlpineArch=armv7 __QEMUArch=arm __UbuntuArch=armhf __UbuntuRepo="http://ports.ubuntu.com/" __LLDB_Package="liblldb-3.9-dev" __SkipUnmount=0 # base development support __UbuntuPackages="build-essential" __AlpinePackages="alpine-base" __AlpinePackages+=" build-base" __AlpinePackages+=" linux-headers" __AlpinePackages+=" lldb-dev" __AlpinePackages+=" python3" __AlpinePackages+=" libedit" # symlinks fixer __UbuntuPackages+=" symlinks" # CoreCLR and CoreFX dependencies __UbuntuPackages+=" libicu-dev" __UbuntuPackages+=" liblttng-ust-dev" __UbuntuPackages+=" libunwind8-dev" __AlpinePackages+=" gettext-dev" __AlpinePackages+=" icu-dev" __AlpinePackages+=" libunwind-dev" __AlpinePackages+=" lttng-ust-dev" # CoreFX dependencies __UbuntuPackages+=" libcurl4-openssl-dev" __UbuntuPackages+=" libkrb5-dev" __UbuntuPackages+=" libssl-dev" __UbuntuPackages+=" zlib1g-dev" __AlpinePackages+=" curl-dev" __AlpinePackages+=" krb5-dev" __AlpinePackages+=" openssl-dev" __AlpinePackages+=" zlib-dev" __FreeBSDBase="12.2-RELEASE" __FreeBSDPkg="1.12.0" __FreeBSDABI="12" __FreeBSDPackages="libunwind" __FreeBSDPackages+=" icu" __FreeBSDPackages+=" libinotify" __FreeBSDPackages+=" lttng-ust" __FreeBSDPackages+=" krb5" __FreeBSDPackages+=" terminfo-db" __IllumosPackages="icu-64.2nb2" __IllumosPackages+=" mit-krb5-1.16.2nb4" __IllumosPackages+=" openssl-1.1.1e" __IllumosPackages+=" zlib-1.2.11" # ML.NET dependencies __UbuntuPackages+=" libomp5" __UbuntuPackages+=" libomp-dev" __UseMirror=0 __UnprocessedBuildArgs= while :; do if [ $# -le 0 ]; then break fi lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" case $lowerI in -?|-h|--help) usage exit 1 ;; arm) __BuildArch=arm __UbuntuArch=armhf __AlpineArch=armv7 __QEMUArch=arm ;; arm64) __BuildArch=arm64 __UbuntuArch=arm64 __AlpineArch=aarch64 __QEMUArch=aarch64 ;; armel) __BuildArch=armel __UbuntuArch=armel __UbuntuRepo="http://ftp.debian.org/debian/" __CodeName=jessie ;; s390x) __BuildArch=s390x __UbuntuArch=s390x __UbuntuRepo="http://ports.ubuntu.com/ubuntu-ports/" __UbuntuPackages=$(echo ${__UbuntuPackages} | sed 's/ libunwind8-dev//') __UbuntuPackages=$(echo ${__UbuntuPackages} | sed 's/ libomp-dev//') __UbuntuPackages=$(echo ${__UbuntuPackages} | sed 's/ libomp5//') unset __LLDB_Package ;; x86) __BuildArch=x86 __UbuntuArch=i386 __UbuntuRepo="http://archive.ubuntu.com/ubuntu/" ;; lldb3.6) __LLDB_Package="lldb-3.6-dev" ;; lldb3.8) __LLDB_Package="lldb-3.8-dev" ;; lldb3.9) __LLDB_Package="liblldb-3.9-dev" ;; lldb4.0) __LLDB_Package="liblldb-4.0-dev" ;; lldb5.0) __LLDB_Package="liblldb-5.0-dev" ;; lldb6.0) __LLDB_Package="liblldb-6.0-dev" ;; no-lldb) unset __LLDB_Package ;; xenial) # Ubuntu 16.04 if [ "$__CodeName" != "jessie" ]; then __CodeName=xenial fi ;; zesty) # Ubuntu 17.04 if [ "$__CodeName" != "jessie" ]; then __CodeName=zesty fi ;; bionic) # Ubuntu 18.04 if [ "$__CodeName" != "jessie" ]; then __CodeName=bionic fi ;; jessie) # Debian 8 __CodeName=jessie __UbuntuRepo="http://ftp.debian.org/debian/" ;; stretch) # Debian 9 __CodeName=stretch __UbuntuRepo="http://ftp.debian.org/debian/" __LLDB_Package="liblldb-6.0-dev" ;; buster) # Debian 10 __CodeName=buster __UbuntuRepo="http://ftp.debian.org/debian/" __LLDB_Package="liblldb-6.0-dev" ;; tizen) if [ "$__BuildArch" != "armel" ] && [ "$__BuildArch" != "arm64" ]; then echo "Tizen is available only for armel and arm64." usage; exit 1; fi __CodeName= __UbuntuRepo= __Tizen=tizen ;; alpine|alpine3.13) __CodeName=alpine __UbuntuRepo= __AlpineVersion=3.13 __AlpinePackages+=" llvm10-libs" ;; alpine3.14) __CodeName=alpine __UbuntuRepo= __AlpineVersion=3.14 __AlpinePackages+=" llvm11-libs" ;; freebsd11) __FreeBSDBase="11.3-RELEASE" __FreeBSDABI="11" ;& freebsd12) __CodeName=freebsd __BuildArch=x64 __SkipUnmount=1 ;; freebsd13) __CodeName=freebsd __FreeBSDBase="13.0-RELEASE" __FreeBSDABI="13" __BuildArch=x64 __SkipUnmount=1 ;; illumos) __CodeName=illumos __BuildArch=x64 __SkipUnmount=1 ;; --skipunmount) __SkipUnmount=1 ;; --rootfsdir|-rootfsdir) shift __RootfsDir=$1 ;; --use-mirror) __UseMirror=1 ;; *) __UnprocessedBuildArgs="$__UnprocessedBuildArgs $1" ;; esac shift done if [ "$__BuildArch" == "armel" ]; then __LLDB_Package="lldb-3.5-dev" fi __UbuntuPackages+=" ${__LLDB_Package:-}" if [ -z "$__RootfsDir" ] && [ ! -z "$ROOTFS_DIR" ]; then __RootfsDir=$ROOTFS_DIR fi if [ -z "$__RootfsDir" ]; then __RootfsDir="$__CrossDir/../../../.tools/rootfs/$__BuildArch" fi if [ -d "$__RootfsDir" ]; then if [ $__SkipUnmount == 0 ]; then umount $__RootfsDir/* || true fi rm -rf $__RootfsDir fi mkdir -p $__RootfsDir __RootfsDir="$( cd "$__RootfsDir" && pwd )" if [[ "$__CodeName" == "alpine" ]]; then __ApkToolsVersion=2.9.1 __ApkToolsDir=$(mktemp -d) wget https://github.com/alpinelinux/apk-tools/releases/download/v$__ApkToolsVersion/apk-tools-$__ApkToolsVersion-x86_64-linux.tar.gz -P $__ApkToolsDir tar -xf $__ApkToolsDir/apk-tools-$__ApkToolsVersion-x86_64-linux.tar.gz -C $__ApkToolsDir mkdir -p $__RootfsDir/usr/bin cp -v /usr/bin/qemu-$__QEMUArch-static $__RootfsDir/usr/bin $__ApkToolsDir/apk-tools-$__ApkToolsVersion/apk \ -X http://dl-cdn.alpinelinux.org/alpine/v$__AlpineVersion/main \ -X http://dl-cdn.alpinelinux.org/alpine/v$__AlpineVersion/community \ -U --allow-untrusted --root $__RootfsDir --arch $__AlpineArch --initdb \ add $__AlpinePackages rm -r $__ApkToolsDir elif [[ "$__CodeName" == "freebsd" ]]; then mkdir -p $__RootfsDir/usr/local/etc JOBS="$(getconf _NPROCESSORS_ONLN)" wget -O - https://download.freebsd.org/ftp/releases/amd64/${__FreeBSDBase}/base.txz | tar -C $__RootfsDir -Jxf - ./lib ./usr/lib ./usr/libdata ./usr/include ./usr/share/keys ./etc ./bin/freebsd-version echo "ABI = \"FreeBSD:${__FreeBSDABI}:amd64\"; FINGERPRINTS = \"${__RootfsDir}/usr/share/keys\"; REPOS_DIR = [\"${__RootfsDir}/etc/pkg\"]; REPO_AUTOUPDATE = NO; RUN_SCRIPTS = NO;" > ${__RootfsDir}/usr/local/etc/pkg.conf echo "FreeBSD: { url: "pkg+http://pkg.FreeBSD.org/\${ABI}/quarterly", mirror_type: \"srv\", signature_type: \"fingerprints\", fingerprints: \"${__RootfsDir}/usr/share/keys/pkg\", enabled: yes }" > ${__RootfsDir}/etc/pkg/FreeBSD.conf mkdir -p $__RootfsDir/tmp # get and build package manager wget -O - https://github.com/freebsd/pkg/archive/${__FreeBSDPkg}.tar.gz | tar -C $__RootfsDir/tmp -zxf - cd $__RootfsDir/tmp/pkg-${__FreeBSDPkg} # needed for install to succeed mkdir -p $__RootfsDir/host/etc ./autogen.sh && ./configure --prefix=$__RootfsDir/host && make -j "$JOBS" && make install rm -rf $__RootfsDir/tmp/pkg-${__FreeBSDPkg} # install packages we need. INSTALL_AS_USER=$(whoami) $__RootfsDir/host/sbin/pkg -r $__RootfsDir -C $__RootfsDir/usr/local/etc/pkg.conf update INSTALL_AS_USER=$(whoami) $__RootfsDir/host/sbin/pkg -r $__RootfsDir -C $__RootfsDir/usr/local/etc/pkg.conf install --yes $__FreeBSDPackages elif [[ "$__CodeName" == "illumos" ]]; then mkdir "$__RootfsDir/tmp" pushd "$__RootfsDir/tmp" JOBS="$(getconf _NPROCESSORS_ONLN)" echo "Downloading sysroot." wget -O - https://github.com/illumos/sysroot/releases/download/20181213-de6af22ae73b-v1/illumos-sysroot-i386-20181213-de6af22ae73b-v1.tar.gz | tar -C "$__RootfsDir" -xzf - echo "Building binutils. Please wait.." wget -O - https://ftp.gnu.org/gnu/binutils/binutils-2.33.1.tar.bz2 | tar -xjf - mkdir build-binutils && cd build-binutils ../binutils-2.33.1/configure --prefix="$__RootfsDir" --target="x86_64-sun-solaris2.10" --program-prefix="x86_64-illumos-" --with-sysroot="$__RootfsDir" make -j "$JOBS" && make install && cd .. echo "Building gcc. Please wait.." wget -O - https://ftp.gnu.org/gnu/gcc/gcc-8.4.0/gcc-8.4.0.tar.xz | tar -xJf - CFLAGS="-fPIC" CXXFLAGS="-fPIC" CXXFLAGS_FOR_TARGET="-fPIC" CFLAGS_FOR_TARGET="-fPIC" export CFLAGS CXXFLAGS CXXFLAGS_FOR_TARGET CFLAGS_FOR_TARGET mkdir build-gcc && cd build-gcc ../gcc-8.4.0/configure --prefix="$__RootfsDir" --target="x86_64-sun-solaris2.10" --program-prefix="x86_64-illumos-" --with-sysroot="$__RootfsDir" --with-gnu-as \ --with-gnu-ld --disable-nls --disable-libgomp --disable-libquadmath --disable-libssp --disable-libvtv --disable-libcilkrts --disable-libada --disable-libsanitizer \ --disable-libquadmath-support --disable-shared --enable-tls make -j "$JOBS" && make install && cd .. BaseUrl=https://pkgsrc.joyent.com if [[ "$__UseMirror" == 1 ]]; then BaseUrl=http://pkgsrc.smartos.skylime.net fi BaseUrl="$BaseUrl"/packages/SmartOS/2020Q1/x86_64/All echo "Downloading dependencies." read -ra array <<<"$__IllumosPackages" for package in "${array[@]}"; do echo "Installing $package..." wget "$BaseUrl"/"$package".tgz ar -x "$package".tgz tar --skip-old-files -xzf "$package".tmp.tgz -C "$__RootfsDir" 2>/dev/null done echo "Cleaning up temporary files." popd rm -rf "$__RootfsDir"/{tmp,+*} mkdir -p "$__RootfsDir"/usr/include/net mkdir -p "$__RootfsDir"/usr/include/netpacket wget -P "$__RootfsDir"/usr/include/net https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/io/bpf/net/bpf.h wget -P "$__RootfsDir"/usr/include/net https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/io/bpf/net/dlt.h wget -P "$__RootfsDir"/usr/include/netpacket https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/inet/sockmods/netpacket/packet.h wget -P "$__RootfsDir"/usr/include/sys https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/sys/sdt.h elif [[ -n $__CodeName ]]; then qemu-debootstrap --arch $__UbuntuArch $__CodeName $__RootfsDir $__UbuntuRepo cp $__CrossDir/$__BuildArch/sources.list.$__CodeName $__RootfsDir/etc/apt/sources.list chroot $__RootfsDir apt-get update chroot $__RootfsDir apt-get -f -y install chroot $__RootfsDir apt-get -y install $__UbuntuPackages chroot $__RootfsDir symlinks -cr /usr chroot $__RootfsDir apt-get clean if [ $__SkipUnmount == 0 ]; then umount $__RootfsDir/* || true fi if [[ "$__BuildArch" == "armel" && "$__CodeName" == "jessie" ]]; then pushd $__RootfsDir patch -p1 < $__CrossDir/$__BuildArch/armel.jessie.patch popd fi elif [[ "$__Tizen" == "tizen" ]]; then ROOTFS_DIR=$__RootfsDir $__CrossDir/$__BuildArch/tizen-build-rootfs.sh else echo "Unsupported target platform." usage; exit 1 fi
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/cross/toolchain.cmake
set(CROSS_ROOTFS $ENV{ROOTFS_DIR}) set(TARGET_ARCH_NAME $ENV{TARGET_BUILD_ARCH}) if(EXISTS ${CROSS_ROOTFS}/bin/freebsd-version) set(CMAKE_SYSTEM_NAME FreeBSD) elseif(EXISTS ${CROSS_ROOTFS}/usr/platform/i86pc) set(CMAKE_SYSTEM_NAME SunOS) set(ILLUMOS 1) else() set(CMAKE_SYSTEM_NAME Linux) endif() set(CMAKE_SYSTEM_VERSION 1) if(TARGET_ARCH_NAME STREQUAL "armel") set(CMAKE_SYSTEM_PROCESSOR armv7l) set(TOOLCHAIN "arm-linux-gnueabi") if("$ENV{__DistroRid}" MATCHES "tizen.*") set(TIZEN_TOOLCHAIN "armv7l-tizen-linux-gnueabi/9.2.0") endif() elseif(TARGET_ARCH_NAME STREQUAL "arm") set(CMAKE_SYSTEM_PROCESSOR armv7l) if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/armv7-alpine-linux-musleabihf) set(TOOLCHAIN "armv7-alpine-linux-musleabihf") elseif(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/armv6-alpine-linux-musleabihf) set(TOOLCHAIN "armv6-alpine-linux-musleabihf") else() set(TOOLCHAIN "arm-linux-gnueabihf") endif() elseif(TARGET_ARCH_NAME STREQUAL "arm64") set(CMAKE_SYSTEM_PROCESSOR aarch64) if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/aarch64-alpine-linux-musl) set(TOOLCHAIN "aarch64-alpine-linux-musl") else() set(TOOLCHAIN "aarch64-linux-gnu") endif() if("$ENV{__DistroRid}" MATCHES "tizen.*") set(TIZEN_TOOLCHAIN "aarch64-tizen-linux-gnu/9.2.0") endif() elseif(TARGET_ARCH_NAME STREQUAL "s390x") set(CMAKE_SYSTEM_PROCESSOR s390x) set(TOOLCHAIN "s390x-linux-gnu") elseif(TARGET_ARCH_NAME STREQUAL "x86") set(CMAKE_SYSTEM_PROCESSOR i686) set(TOOLCHAIN "i686-linux-gnu") elseif (CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") set(CMAKE_SYSTEM_PROCESSOR "x86_64") set(triple "x86_64-unknown-freebsd11") elseif (ILLUMOS) set(CMAKE_SYSTEM_PROCESSOR "x86_64") set(TOOLCHAIN "x86_64-illumos") else() message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only armel, arm, arm64, s390x and x86 are supported!") endif() if(DEFINED ENV{TOOLCHAIN}) set(TOOLCHAIN $ENV{TOOLCHAIN}) endif() # Specify include paths if(DEFINED TIZEN_TOOLCHAIN) if(TARGET_ARCH_NAME STREQUAL "armel") include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}/include/c++/) include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}/include/c++/armv7l-tizen-linux-gnueabi) endif() if(TARGET_ARCH_NAME STREQUAL "arm64") include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}/include/c++/) include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}/include/c++/aarch64-tizen-linux-gnu) endif() endif() if("$ENV{__DistroRid}" MATCHES "android.*") if(TARGET_ARCH_NAME STREQUAL "arm") set(ANDROID_ABI armeabi-v7a) elseif(TARGET_ARCH_NAME STREQUAL "arm64") set(ANDROID_ABI arm64-v8a) endif() # extract platform number required by the NDK's toolchain string(REGEX REPLACE ".*\\.([0-9]+)-.*" "\\1" ANDROID_PLATFORM "$ENV{__DistroRid}") set(ANDROID_TOOLCHAIN clang) set(FEATURE_EVENT_TRACE 0) # disable event trace as there is no lttng-ust package in termux repository set(CMAKE_SYSTEM_LIBRARY_PATH "${CROSS_ROOTFS}/usr/lib") set(CMAKE_SYSTEM_INCLUDE_PATH "${CROSS_ROOTFS}/usr/include") # include official NDK toolchain script include(${CROSS_ROOTFS}/../build/cmake/android.toolchain.cmake) elseif(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") # we cross-compile by instructing clang set(CMAKE_C_COMPILER_TARGET ${triple}) set(CMAKE_CXX_COMPILER_TARGET ${triple}) set(CMAKE_ASM_COMPILER_TARGET ${triple}) set(CMAKE_SYSROOT "${CROSS_ROOTFS}") elseif(ILLUMOS) set(CMAKE_SYSROOT "${CROSS_ROOTFS}") include_directories(SYSTEM ${CROSS_ROOTFS}/include) set(TOOLSET_PREFIX ${TOOLCHAIN}-) function(locate_toolchain_exec exec var) string(TOUPPER ${exec} EXEC_UPPERCASE) if(NOT "$ENV{CLR_${EXEC_UPPERCASE}}" STREQUAL "") set(${var} "$ENV{CLR_${EXEC_UPPERCASE}}" PARENT_SCOPE) return() endif() find_program(EXEC_LOCATION_${exec} NAMES "${TOOLSET_PREFIX}${exec}${CLR_CMAKE_COMPILER_FILE_NAME_VERSION}" "${TOOLSET_PREFIX}${exec}") if (EXEC_LOCATION_${exec} STREQUAL "EXEC_LOCATION_${exec}-NOTFOUND") message(FATAL_ERROR "Unable to find toolchain executable. Name: ${exec}, Prefix: ${TOOLSET_PREFIX}.") endif() set(${var} ${EXEC_LOCATION_${exec}} PARENT_SCOPE) endfunction() set(CMAKE_SYSTEM_PREFIX_PATH "${CROSS_ROOTFS}") locate_toolchain_exec(gcc CMAKE_C_COMPILER) locate_toolchain_exec(g++ CMAKE_CXX_COMPILER) set(CMAKE_C_STANDARD_LIBRARIES "${CMAKE_C_STANDARD_LIBRARIES} -lssp") set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -lssp") else() set(CMAKE_SYSROOT "${CROSS_ROOTFS}") set(CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN "${CROSS_ROOTFS}/usr") set(CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN "${CROSS_ROOTFS}/usr") set(CMAKE_ASM_COMPILER_EXTERNAL_TOOLCHAIN "${CROSS_ROOTFS}/usr") endif() # Specify link flags function(add_toolchain_linker_flag Flag) set(Config "${ARGV1}") set(CONFIG_SUFFIX "") if (NOT Config STREQUAL "") set(CONFIG_SUFFIX "_${Config}") endif() set("CMAKE_EXE_LINKER_FLAGS${CONFIG_SUFFIX}" "${CMAKE_EXE_LINKER_FLAGS${CONFIG_SUFFIX}} ${Flag}" PARENT_SCOPE) set("CMAKE_SHARED_LINKER_FLAGS${CONFIG_SUFFIX}" "${CMAKE_SHARED_LINKER_FLAGS${CONFIG_SUFFIX}} ${Flag}" PARENT_SCOPE) endfunction() if(CMAKE_SYSTEM_NAME STREQUAL "Linux") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/lib/${TOOLCHAIN}") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/usr/lib/${TOOLCHAIN}") endif() if(TARGET_ARCH_NAME STREQUAL "armel") if(DEFINED TIZEN_TOOLCHAIN) # For Tizen only add_toolchain_linker_flag("-B${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/lib") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}") endif() elseif(TARGET_ARCH_NAME STREQUAL "arm64") if(DEFINED TIZEN_TOOLCHAIN) # For Tizen only add_toolchain_linker_flag("-B${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/lib64") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib64") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/lib64") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/usr/lib64") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}") endif() elseif(TARGET_ARCH_NAME STREQUAL "x86") add_toolchain_linker_flag(-m32) elseif(ILLUMOS) add_toolchain_linker_flag("-L${CROSS_ROOTFS}/lib/amd64") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/amd64/lib") endif() # Specify compile options if((TARGET_ARCH_NAME MATCHES "^(arm|armel|arm64|s390x)$" AND NOT "$ENV{__DistroRid}" MATCHES "android.*") OR ILLUMOS) set(CMAKE_C_COMPILER_TARGET ${TOOLCHAIN}) set(CMAKE_CXX_COMPILER_TARGET ${TOOLCHAIN}) set(CMAKE_ASM_COMPILER_TARGET ${TOOLCHAIN}) endif() if(TARGET_ARCH_NAME MATCHES "^(arm|armel)$") add_compile_options(-mthumb) if (NOT DEFINED CLR_ARM_FPU_TYPE) set (CLR_ARM_FPU_TYPE vfpv3) endif (NOT DEFINED CLR_ARM_FPU_TYPE) add_compile_options (-mfpu=${CLR_ARM_FPU_TYPE}) if (NOT DEFINED CLR_ARM_FPU_CAPABILITY) set (CLR_ARM_FPU_CAPABILITY 0x7) endif (NOT DEFINED CLR_ARM_FPU_CAPABILITY) add_definitions (-DCLR_ARM_FPU_CAPABILITY=${CLR_ARM_FPU_CAPABILITY}) if(TARGET_ARCH_NAME STREQUAL "armel") add_compile_options(-mfloat-abi=softfp) endif() elseif(TARGET_ARCH_NAME STREQUAL "x86") add_compile_options(-m32) add_compile_options(-Wno-error=unused-command-line-argument) endif() if(DEFINED TIZEN_TOOLCHAIN) if(TARGET_ARCH_NAME MATCHES "^(armel|arm64)$") add_compile_options(-Wno-deprecated-declarations) # compile-time option add_compile_options(-D__extern_always_inline=inline) # compile-time option endif() endif() # Set LLDB include and library paths for builds that need lldb. if(TARGET_ARCH_NAME MATCHES "^(arm|armel|x86)$") if(TARGET_ARCH_NAME STREQUAL "x86") set(LLVM_CROSS_DIR "$ENV{LLVM_CROSS_HOME}") else() # arm/armel case set(LLVM_CROSS_DIR "$ENV{LLVM_ARM_HOME}") endif() if(LLVM_CROSS_DIR) set(WITH_LLDB_LIBS "${LLVM_CROSS_DIR}/lib/" CACHE STRING "") set(WITH_LLDB_INCLUDES "${LLVM_CROSS_DIR}/include" CACHE STRING "") set(LLDB_H "${WITH_LLDB_INCLUDES}" CACHE STRING "") set(LLDB "${LLVM_CROSS_DIR}/lib/liblldb.so" CACHE STRING "") else() if(TARGET_ARCH_NAME STREQUAL "x86") set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/i386-linux-gnu" CACHE STRING "") set(CHECK_LLVM_DIR "${CROSS_ROOTFS}/usr/lib/llvm-3.8/include") if(EXISTS "${CHECK_LLVM_DIR}" AND IS_DIRECTORY "${CHECK_LLVM_DIR}") set(WITH_LLDB_INCLUDES "${CHECK_LLVM_DIR}") else() set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include") endif() else() # arm/armel case set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/${TOOLCHAIN}" CACHE STRING "") set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include" CACHE STRING "") endif() endif() endif() set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(CROSS_ROOTFS $ENV{ROOTFS_DIR}) set(TARGET_ARCH_NAME $ENV{TARGET_BUILD_ARCH}) if(EXISTS ${CROSS_ROOTFS}/bin/freebsd-version) set(CMAKE_SYSTEM_NAME FreeBSD) elseif(EXISTS ${CROSS_ROOTFS}/usr/platform/i86pc) set(CMAKE_SYSTEM_NAME SunOS) set(ILLUMOS 1) else() set(CMAKE_SYSTEM_NAME Linux) endif() set(CMAKE_SYSTEM_VERSION 1) if(TARGET_ARCH_NAME STREQUAL "armel") set(CMAKE_SYSTEM_PROCESSOR armv7l) set(TOOLCHAIN "arm-linux-gnueabi") if("$ENV{__DistroRid}" MATCHES "tizen.*") set(TIZEN_TOOLCHAIN "armv7l-tizen-linux-gnueabi/9.2.0") endif() elseif(TARGET_ARCH_NAME STREQUAL "arm") set(CMAKE_SYSTEM_PROCESSOR armv7l) if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/armv7-alpine-linux-musleabihf) set(TOOLCHAIN "armv7-alpine-linux-musleabihf") elseif(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/armv6-alpine-linux-musleabihf) set(TOOLCHAIN "armv6-alpine-linux-musleabihf") else() set(TOOLCHAIN "arm-linux-gnueabihf") endif() elseif(TARGET_ARCH_NAME STREQUAL "arm64") set(CMAKE_SYSTEM_PROCESSOR aarch64) if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/aarch64-alpine-linux-musl) set(TOOLCHAIN "aarch64-alpine-linux-musl") else() set(TOOLCHAIN "aarch64-linux-gnu") endif() if("$ENV{__DistroRid}" MATCHES "tizen.*") set(TIZEN_TOOLCHAIN "aarch64-tizen-linux-gnu/9.2.0") endif() elseif(TARGET_ARCH_NAME STREQUAL "s390x") set(CMAKE_SYSTEM_PROCESSOR s390x) set(TOOLCHAIN "s390x-linux-gnu") elseif(TARGET_ARCH_NAME STREQUAL "x86") set(CMAKE_SYSTEM_PROCESSOR i686) set(TOOLCHAIN "i686-linux-gnu") elseif (CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") set(CMAKE_SYSTEM_PROCESSOR "x86_64") set(triple "x86_64-unknown-freebsd12") elseif (ILLUMOS) set(CMAKE_SYSTEM_PROCESSOR "x86_64") set(TOOLCHAIN "x86_64-illumos") else() message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only armel, arm, arm64, s390x and x86 are supported!") endif() if(DEFINED ENV{TOOLCHAIN}) set(TOOLCHAIN $ENV{TOOLCHAIN}) endif() # Specify include paths if(DEFINED TIZEN_TOOLCHAIN) if(TARGET_ARCH_NAME STREQUAL "armel") include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}/include/c++/) include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}/include/c++/armv7l-tizen-linux-gnueabi) endif() if(TARGET_ARCH_NAME STREQUAL "arm64") include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}/include/c++/) include_directories(SYSTEM ${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}/include/c++/aarch64-tizen-linux-gnu) endif() endif() if("$ENV{__DistroRid}" MATCHES "android.*") if(TARGET_ARCH_NAME STREQUAL "arm") set(ANDROID_ABI armeabi-v7a) elseif(TARGET_ARCH_NAME STREQUAL "arm64") set(ANDROID_ABI arm64-v8a) endif() # extract platform number required by the NDK's toolchain string(REGEX REPLACE ".*\\.([0-9]+)-.*" "\\1" ANDROID_PLATFORM "$ENV{__DistroRid}") set(ANDROID_TOOLCHAIN clang) set(FEATURE_EVENT_TRACE 0) # disable event trace as there is no lttng-ust package in termux repository set(CMAKE_SYSTEM_LIBRARY_PATH "${CROSS_ROOTFS}/usr/lib") set(CMAKE_SYSTEM_INCLUDE_PATH "${CROSS_ROOTFS}/usr/include") # include official NDK toolchain script include(${CROSS_ROOTFS}/../build/cmake/android.toolchain.cmake) elseif(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") # we cross-compile by instructing clang set(CMAKE_C_COMPILER_TARGET ${triple}) set(CMAKE_CXX_COMPILER_TARGET ${triple}) set(CMAKE_ASM_COMPILER_TARGET ${triple}) set(CMAKE_SYSROOT "${CROSS_ROOTFS}") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fuse-ld=lld") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fuse-ld=lld") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -fuse-ld=lld") elseif(ILLUMOS) set(CMAKE_SYSROOT "${CROSS_ROOTFS}") include_directories(SYSTEM ${CROSS_ROOTFS}/include) set(TOOLSET_PREFIX ${TOOLCHAIN}-) function(locate_toolchain_exec exec var) string(TOUPPER ${exec} EXEC_UPPERCASE) if(NOT "$ENV{CLR_${EXEC_UPPERCASE}}" STREQUAL "") set(${var} "$ENV{CLR_${EXEC_UPPERCASE}}" PARENT_SCOPE) return() endif() find_program(EXEC_LOCATION_${exec} NAMES "${TOOLSET_PREFIX}${exec}${CLR_CMAKE_COMPILER_FILE_NAME_VERSION}" "${TOOLSET_PREFIX}${exec}") if (EXEC_LOCATION_${exec} STREQUAL "EXEC_LOCATION_${exec}-NOTFOUND") message(FATAL_ERROR "Unable to find toolchain executable. Name: ${exec}, Prefix: ${TOOLSET_PREFIX}.") endif() set(${var} ${EXEC_LOCATION_${exec}} PARENT_SCOPE) endfunction() set(CMAKE_SYSTEM_PREFIX_PATH "${CROSS_ROOTFS}") locate_toolchain_exec(gcc CMAKE_C_COMPILER) locate_toolchain_exec(g++ CMAKE_CXX_COMPILER) set(CMAKE_C_STANDARD_LIBRARIES "${CMAKE_C_STANDARD_LIBRARIES} -lssp") set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -lssp") else() set(CMAKE_SYSROOT "${CROSS_ROOTFS}") set(CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN "${CROSS_ROOTFS}/usr") set(CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN "${CROSS_ROOTFS}/usr") set(CMAKE_ASM_COMPILER_EXTERNAL_TOOLCHAIN "${CROSS_ROOTFS}/usr") endif() # Specify link flags function(add_toolchain_linker_flag Flag) set(Config "${ARGV1}") set(CONFIG_SUFFIX "") if (NOT Config STREQUAL "") set(CONFIG_SUFFIX "_${Config}") endif() set("CMAKE_EXE_LINKER_FLAGS${CONFIG_SUFFIX}_INIT" "${CMAKE_EXE_LINKER_FLAGS${CONFIG_SUFFIX}_INIT} ${Flag}" PARENT_SCOPE) set("CMAKE_SHARED_LINKER_FLAGS${CONFIG_SUFFIX}_INIT" "${CMAKE_SHARED_LINKER_FLAGS${CONFIG_SUFFIX}_INIT} ${Flag}" PARENT_SCOPE) endfunction() if(CMAKE_SYSTEM_NAME STREQUAL "Linux") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/lib/${TOOLCHAIN}") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/usr/lib/${TOOLCHAIN}") endif() if(TARGET_ARCH_NAME STREQUAL "armel") if(DEFINED TIZEN_TOOLCHAIN) # For Tizen only add_toolchain_linker_flag("-B${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/lib") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib/gcc/${TIZEN_TOOLCHAIN}") endif() elseif(TARGET_ARCH_NAME STREQUAL "arm64") if(DEFINED TIZEN_TOOLCHAIN) # For Tizen only add_toolchain_linker_flag("-B${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/lib64") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib64") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/lib64") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/usr/lib64") add_toolchain_linker_flag("-Wl,--rpath-link=${CROSS_ROOTFS}/usr/lib64/gcc/${TIZEN_TOOLCHAIN}") endif() elseif(TARGET_ARCH_NAME STREQUAL "x86") add_toolchain_linker_flag(-m32) elseif(ILLUMOS) add_toolchain_linker_flag("-L${CROSS_ROOTFS}/lib/amd64") add_toolchain_linker_flag("-L${CROSS_ROOTFS}/usr/amd64/lib") endif() # Specify compile options if((TARGET_ARCH_NAME MATCHES "^(arm|armel|arm64|s390x)$" AND NOT "$ENV{__DistroRid}" MATCHES "android.*") OR ILLUMOS) set(CMAKE_C_COMPILER_TARGET ${TOOLCHAIN}) set(CMAKE_CXX_COMPILER_TARGET ${TOOLCHAIN}) set(CMAKE_ASM_COMPILER_TARGET ${TOOLCHAIN}) endif() if(TARGET_ARCH_NAME MATCHES "^(arm|armel)$") add_compile_options(-mthumb) if (NOT DEFINED CLR_ARM_FPU_TYPE) set (CLR_ARM_FPU_TYPE vfpv3) endif (NOT DEFINED CLR_ARM_FPU_TYPE) add_compile_options (-mfpu=${CLR_ARM_FPU_TYPE}) if (NOT DEFINED CLR_ARM_FPU_CAPABILITY) set (CLR_ARM_FPU_CAPABILITY 0x7) endif (NOT DEFINED CLR_ARM_FPU_CAPABILITY) add_definitions (-DCLR_ARM_FPU_CAPABILITY=${CLR_ARM_FPU_CAPABILITY}) if(TARGET_ARCH_NAME STREQUAL "armel") add_compile_options(-mfloat-abi=softfp) endif() elseif(TARGET_ARCH_NAME STREQUAL "x86") add_compile_options(-m32) add_compile_options(-Wno-error=unused-command-line-argument) endif() if(DEFINED TIZEN_TOOLCHAIN) if(TARGET_ARCH_NAME MATCHES "^(armel|arm64)$") add_compile_options(-Wno-deprecated-declarations) # compile-time option add_compile_options(-D__extern_always_inline=inline) # compile-time option endif() endif() # Set LLDB include and library paths for builds that need lldb. if(TARGET_ARCH_NAME MATCHES "^(arm|armel|x86)$") if(TARGET_ARCH_NAME STREQUAL "x86") set(LLVM_CROSS_DIR "$ENV{LLVM_CROSS_HOME}") else() # arm/armel case set(LLVM_CROSS_DIR "$ENV{LLVM_ARM_HOME}") endif() if(LLVM_CROSS_DIR) set(WITH_LLDB_LIBS "${LLVM_CROSS_DIR}/lib/" CACHE STRING "") set(WITH_LLDB_INCLUDES "${LLVM_CROSS_DIR}/include" CACHE STRING "") set(LLDB_H "${WITH_LLDB_INCLUDES}" CACHE STRING "") set(LLDB "${LLVM_CROSS_DIR}/lib/liblldb.so" CACHE STRING "") else() if(TARGET_ARCH_NAME STREQUAL "x86") set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/i386-linux-gnu" CACHE STRING "") set(CHECK_LLVM_DIR "${CROSS_ROOTFS}/usr/lib/llvm-3.8/include") if(EXISTS "${CHECK_LLVM_DIR}" AND IS_DIRECTORY "${CHECK_LLVM_DIR}") set(WITH_LLDB_INCLUDES "${CHECK_LLVM_DIR}") else() set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include") endif() else() # arm/armel case set(WITH_LLDB_LIBS "${CROSS_ROOTFS}/usr/lib/${TOOLCHAIN}" CACHE STRING "") set(WITH_LLDB_INCLUDES "${CROSS_ROOTFS}/usr/lib/llvm-3.6/include" CACHE STRING "") endif() endif() endif() set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/init-tools-native.sh
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" base_uri='https://netcorenativeassets.blob.core.windows.net/resource-packages/external' install_directory='' clean=false force=false download_retries=5 retry_wait_time_seconds=30 global_json_file="$(dirname "$(dirname "${scriptroot}")")/global.json" declare -A native_assets . $scriptroot/pipeline-logging-functions.sh . $scriptroot/native/common-library.sh while (($# > 0)); do lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" case $lowerI in --baseuri) base_uri=$2 shift 2 ;; --installdirectory) install_directory=$2 shift 2 ;; --clean) clean=true shift 1 ;; --force) force=true shift 1 ;; --donotabortonfailure) donotabortonfailure=true shift 1 ;; --donotdisplaywarnings) donotdisplaywarnings=true shift 1 ;; --downloadretries) download_retries=$2 shift 2 ;; --retrywaittimeseconds) retry_wait_time_seconds=$2 shift 2 ;; --help) echo "Common settings:" echo " --installdirectory Directory to install native toolset." echo " This is a command-line override for the default" echo " Install directory precedence order:" echo " - InstallDirectory command-line override" echo " - NETCOREENG_INSTALL_DIRECTORY environment variable" echo " - (default) %USERPROFILE%/.netcoreeng/native" echo "" echo " --clean Switch specifying not to install anything, but cleanup native asset folders" echo " --donotabortonfailure Switch specifiying whether to abort native tools installation on failure" echo " --donotdisplaywarnings Switch specifiying whether to display warnings during native tools installation on failure" echo " --force Clean and then install tools" echo " --help Print help and exit" echo "" echo "Advanced settings:" echo " --baseuri <value> Base URI for where to download native tools from" echo " --downloadretries <value> Number of times a download should be attempted" echo " --retrywaittimeseconds <value> Wait time between download attempts" echo "" exit 0 ;; esac done function ReadGlobalJsonNativeTools { # happy path: we have a proper JSON parsing tool `jq(1)` in PATH! if command -v jq &> /dev/null; then # jq: read each key/value pair under "native-tools" entry and emit: # KEY="<entry-key>" VALUE="<entry-value>" # followed by a null byte. # # bash: read line with null byte delimeter and push to array (for later `eval`uation). while IFS= read -rd '' line; do native_assets+=("$line") done < <(jq -r '. | select(has("native-tools")) | ."native-tools" | keys[] as $k | @sh "KEY=\($k) VALUE=\(.[$k])\u0000"' "$global_json_file") return fi # Warning: falling back to manually parsing JSON, which is not recommended. # Following routine matches the output and escaping logic of jq(1)'s @sh formatter used above. # It has been tested with several weird strings with escaped characters in entries (key and value) # and results were compared with the output of jq(1) in binary representation using xxd(1); # just before the assignment to 'native_assets' array (above and below). # try to capture the section under "native-tools". if [[ ! "$(cat "$global_json_file")" =~ \"native-tools\"[[:space:]\:\{]*([^\}]+) ]]; then return fi section="${BASH_REMATCH[1]}" parseStarted=0 possibleEnd=0 escaping=0 escaped=0 isKey=1 for (( i=0; i<${#section}; i++ )); do char="${section:$i:1}" if ! ((parseStarted)) && [[ "$char" =~ [[:space:],:] ]]; then continue; fi if ! ((escaping)) && [[ "$char" == "\\" ]]; then escaping=1 elif ((escaping)) && ! ((escaped)); then escaped=1 fi if ! ((parseStarted)) && [[ "$char" == "\"" ]]; then parseStarted=1 possibleEnd=0 elif [[ "$char" == "'" ]]; then token="$token'\\\''" possibleEnd=0 elif ((escaping)) || [[ "$char" != "\"" ]]; then token="$token$char" possibleEnd=1 fi if ((possibleEnd)) && ! ((escaping)) && [[ "$char" == "\"" ]]; then # Use printf to unescape token to match jq(1)'s @sh formatting rules. # do not use 'token="$(printf "$token")"' syntax, as $() eats the trailing linefeed. printf -v token "'$token'" if ((isKey)); then KEY="$token" isKey=0 else line="KEY=$KEY VALUE=$token" native_assets+=("$line") isKey=1 fi # reset for next token parseStarted=0 token= elif ((escaping)) && ((escaped)); then escaping=0 escaped=0 fi done } native_base_dir=$install_directory if [[ -z $install_directory ]]; then native_base_dir=$(GetNativeInstallDirectory) fi install_bin="${native_base_dir}/bin" installed_any=false ReadGlobalJsonNativeTools if [[ ${#native_assets[@]} -eq 0 ]]; then echo "No native tools defined in global.json" exit 0; else native_installer_dir="$scriptroot/native" for index in "${!native_assets[@]}"; do eval "${native_assets["$index"]}" installer_path="$native_installer_dir/install-$KEY.sh" installer_command="$installer_path" installer_command+=" --baseuri $base_uri" installer_command+=" --installpath $install_bin" installer_command+=" --version $VALUE" echo $installer_command if [[ $force = true ]]; then installer_command+=" --force" fi if [[ $clean = true ]]; then installer_command+=" --clean" fi if [[ -a $installer_path ]]; then $installer_command if [[ $? != 0 ]]; then if [[ $donotabortonfailure = true ]]; then if [[ $donotdisplaywarnings != true ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Execution Failed" fi else Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Execution Failed" exit 1 fi else $installed_any = true fi else if [[ $donotabortonfailure == true ]]; then if [[ $donotdisplaywarnings != true ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Execution Failed: no install script" fi else Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Execution Failed: no install script" exit 1 fi fi done fi if [[ $clean = true ]]; then exit 0 fi if [[ -d $install_bin ]]; then echo "Native tools are available from $install_bin" echo "##vso[task.prependpath]$install_bin" else if [[ $installed_any = true ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Native tools install directory does not exist, installation failed" exit 1 fi fi exit 0
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" base_uri='https://netcorenativeassets.blob.core.windows.net/resource-packages/external' install_directory='' clean=false force=false download_retries=5 retry_wait_time_seconds=30 global_json_file="$(dirname "$(dirname "${scriptroot}")")/global.json" declare -a native_assets . $scriptroot/pipeline-logging-functions.sh . $scriptroot/native/common-library.sh while (($# > 0)); do lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" case $lowerI in --baseuri) base_uri=$2 shift 2 ;; --installdirectory) install_directory=$2 shift 2 ;; --clean) clean=true shift 1 ;; --force) force=true shift 1 ;; --donotabortonfailure) donotabortonfailure=true shift 1 ;; --donotdisplaywarnings) donotdisplaywarnings=true shift 1 ;; --downloadretries) download_retries=$2 shift 2 ;; --retrywaittimeseconds) retry_wait_time_seconds=$2 shift 2 ;; --help) echo "Common settings:" echo " --installdirectory Directory to install native toolset." echo " This is a command-line override for the default" echo " Install directory precedence order:" echo " - InstallDirectory command-line override" echo " - NETCOREENG_INSTALL_DIRECTORY environment variable" echo " - (default) %USERPROFILE%/.netcoreeng/native" echo "" echo " --clean Switch specifying not to install anything, but cleanup native asset folders" echo " --donotabortonfailure Switch specifiying whether to abort native tools installation on failure" echo " --donotdisplaywarnings Switch specifiying whether to display warnings during native tools installation on failure" echo " --force Clean and then install tools" echo " --help Print help and exit" echo "" echo "Advanced settings:" echo " --baseuri <value> Base URI for where to download native tools from" echo " --downloadretries <value> Number of times a download should be attempted" echo " --retrywaittimeseconds <value> Wait time between download attempts" echo "" exit 0 ;; esac done function ReadGlobalJsonNativeTools { # happy path: we have a proper JSON parsing tool `jq(1)` in PATH! if command -v jq &> /dev/null; then # jq: read each key/value pair under "native-tools" entry and emit: # KEY="<entry-key>" VALUE="<entry-value>" # followed by a null byte. # # bash: read line with null byte delimeter and push to array (for later `eval`uation). while IFS= read -rd '' line; do native_assets+=("$line") done < <(jq -r '. | select(has("native-tools")) | ."native-tools" | keys[] as $k | @sh "KEY=\($k) VALUE=\(.[$k])\u0000"' "$global_json_file") return fi # Warning: falling back to manually parsing JSON, which is not recommended. # Following routine matches the output and escaping logic of jq(1)'s @sh formatter used above. # It has been tested with several weird strings with escaped characters in entries (key and value) # and results were compared with the output of jq(1) in binary representation using xxd(1); # just before the assignment to 'native_assets' array (above and below). # try to capture the section under "native-tools". if [[ ! "$(cat "$global_json_file")" =~ \"native-tools\"[[:space:]\:\{]*([^\}]+) ]]; then return fi section="${BASH_REMATCH[1]}" parseStarted=0 possibleEnd=0 escaping=0 escaped=0 isKey=1 for (( i=0; i<${#section}; i++ )); do char="${section:$i:1}" if ! ((parseStarted)) && [[ "$char" =~ [[:space:],:] ]]; then continue; fi if ! ((escaping)) && [[ "$char" == "\\" ]]; then escaping=1 elif ((escaping)) && ! ((escaped)); then escaped=1 fi if ! ((parseStarted)) && [[ "$char" == "\"" ]]; then parseStarted=1 possibleEnd=0 elif [[ "$char" == "'" ]]; then token="$token'\\\''" possibleEnd=0 elif ((escaping)) || [[ "$char" != "\"" ]]; then token="$token$char" possibleEnd=1 fi if ((possibleEnd)) && ! ((escaping)) && [[ "$char" == "\"" ]]; then # Use printf to unescape token to match jq(1)'s @sh formatting rules. # do not use 'token="$(printf "$token")"' syntax, as $() eats the trailing linefeed. printf -v token "'$token'" if ((isKey)); then KEY="$token" isKey=0 else line="KEY=$KEY VALUE=$token" native_assets+=("$line") isKey=1 fi # reset for next token parseStarted=0 token= elif ((escaping)) && ((escaped)); then escaping=0 escaped=0 fi done } native_base_dir=$install_directory if [[ -z $install_directory ]]; then native_base_dir=$(GetNativeInstallDirectory) fi install_bin="${native_base_dir}/bin" installed_any=false ReadGlobalJsonNativeTools if [[ ${#native_assets[@]} -eq 0 ]]; then echo "No native tools defined in global.json" exit 0; else native_installer_dir="$scriptroot/native" for index in "${!native_assets[@]}"; do eval "${native_assets["$index"]}" installer_path="$native_installer_dir/install-$KEY.sh" installer_command="$installer_path" installer_command+=" --baseuri $base_uri" installer_command+=" --installpath $install_bin" installer_command+=" --version $VALUE" echo $installer_command if [[ $force = true ]]; then installer_command+=" --force" fi if [[ $clean = true ]]; then installer_command+=" --clean" fi if [[ -a $installer_path ]]; then $installer_command if [[ $? != 0 ]]; then if [[ $donotabortonfailure = true ]]; then if [[ $donotdisplaywarnings != true ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Execution Failed" fi else Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Execution Failed" exit 1 fi else $installed_any = true fi else if [[ $donotabortonfailure == true ]]; then if [[ $donotdisplaywarnings != true ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Execution Failed: no install script" fi else Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Execution Failed: no install script" exit 1 fi fi done fi if [[ $clean = true ]]; then exit 0 fi if [[ -d $install_bin ]]; then echo "Native tools are available from $install_bin" echo "##vso[task.prependpath]$install_bin" else if [[ $installed_any = true ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Native tools install directory does not exist, installation failed" exit 1 fi fi exit 0
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/native/common-library.sh
#!/usr/bin/env bash function GetNativeInstallDirectory { local install_dir if [[ -z $NETCOREENG_INSTALL_DIRECTORY ]]; then install_dir=$HOME/.netcoreeng/native/ else install_dir=$NETCOREENG_INSTALL_DIRECTORY fi echo $install_dir return 0 } function GetTempDirectory { echo $(GetNativeInstallDirectory)temp/ return 0 } function ExpandZip { local zip_path=$1 local output_directory=$2 local force=${3:-false} echo "Extracting $zip_path to $output_directory" if [[ -d $output_directory ]] && [[ $force = false ]]; then echo "Directory '$output_directory' already exists, skipping extract" return 0 fi if [[ -d $output_directory ]]; then echo "'Force flag enabled, but '$output_directory' exists. Removing directory" rm -rf $output_directory if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Unable to remove '$output_directory'" return 1 fi fi echo "Creating directory: '$output_directory'" mkdir -p $output_directory echo "Extracting archive" tar -xf $zip_path -C $output_directory if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Unable to extract '$zip_path'" return 1 fi return 0 } function GetCurrentOS { local unameOut="$(uname -s)" case $unameOut in Linux*) echo "Linux";; Darwin*) echo "MacOS";; esac return 0 } function GetFile { local uri=$1 local path=$2 local force=${3:-false} local download_retries=${4:-5} local retry_wait_time_seconds=${5:-30} if [[ -f $path ]]; then if [[ $force = false ]]; then echo "File '$path' already exists. Skipping download" return 0 else rm -rf $path fi fi if [[ -f $uri ]]; then echo "'$uri' is a file path, copying file to '$path'" cp $uri $path return $? fi echo "Downloading $uri" # Use curl if available, otherwise use wget if command -v curl > /dev/null; then curl "$uri" -sSL --retry $download_retries --retry-delay $retry_wait_time_seconds --create-dirs -o "$path" --fail else wget -q -O "$path" "$uri" --tries="$download_retries" fi return $? } function GetTempPathFileName { local path=$1 local temp_dir=$(GetTempDirectory) local temp_file_name=$(basename $path) echo $temp_dir$temp_file_name return 0 } function DownloadAndExtract { local uri=$1 local installDir=$2 local force=${3:-false} local download_retries=${4:-5} local retry_wait_time_seconds=${5:-30} local temp_tool_path=$(GetTempPathFileName $uri) echo "downloading to: $temp_tool_path" # Download file GetFile "$uri" "$temp_tool_path" $force $download_retries $retry_wait_time_seconds if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Failed to download '$uri' to '$temp_tool_path'." return 1 fi # Extract File echo "extracting from $temp_tool_path to $installDir" ExpandZip "$temp_tool_path" "$installDir" $force $download_retries $retry_wait_time_seconds if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Failed to extract '$temp_tool_path' to '$installDir'." return 1 fi return 0 } function NewScriptShim { local shimpath=$1 local tool_file_path=$2 local force=${3:-false} echo "Generating '$shimpath' shim" if [[ -f $shimpath ]]; then if [[ $force = false ]]; then echo "File '$shimpath' already exists." >&2 return 1 else rm -rf $shimpath fi fi if [[ ! -f $tool_file_path ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Specified tool file path:'$tool_file_path' does not exist" return 1 fi local shim_contents=$'#!/usr/bin/env bash\n' shim_contents+="SHIMARGS="$'$1\n' shim_contents+="$tool_file_path"$' $SHIMARGS\n' # Write shim file echo "$shim_contents" > $shimpath chmod +x $shimpath echo "Finished generating shim '$shimpath'" return $? }
#!/usr/bin/env bash function GetNativeInstallDirectory { local install_dir if [[ -z $NETCOREENG_INSTALL_DIRECTORY ]]; then install_dir=$HOME/.netcoreeng/native/ else install_dir=$NETCOREENG_INSTALL_DIRECTORY fi echo $install_dir return 0 } function GetTempDirectory { echo $(GetNativeInstallDirectory)temp/ return 0 } function ExpandZip { local zip_path=$1 local output_directory=$2 local force=${3:-false} echo "Extracting $zip_path to $output_directory" if [[ -d $output_directory ]] && [[ $force = false ]]; then echo "Directory '$output_directory' already exists, skipping extract" return 0 fi if [[ -d $output_directory ]]; then echo "'Force flag enabled, but '$output_directory' exists. Removing directory" rm -rf $output_directory if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Unable to remove '$output_directory'" return 1 fi fi echo "Creating directory: '$output_directory'" mkdir -p $output_directory echo "Extracting archive" tar -xf $zip_path -C $output_directory if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Unable to extract '$zip_path'" return 1 fi return 0 } function GetCurrentOS { local unameOut="$(uname -s)" case $unameOut in Linux*) echo "Linux";; Darwin*) echo "MacOS";; esac return 0 } function GetFile { local uri=$1 local path=$2 local force=${3:-false} local download_retries=${4:-5} local retry_wait_time_seconds=${5:-30} if [[ -f $path ]]; then if [[ $force = false ]]; then echo "File '$path' already exists. Skipping download" return 0 else rm -rf $path fi fi if [[ -f $uri ]]; then echo "'$uri' is a file path, copying file to '$path'" cp $uri $path return $? fi echo "Downloading $uri" # Use curl if available, otherwise use wget if command -v curl > /dev/null; then curl "$uri" -sSL --retry $download_retries --retry-delay $retry_wait_time_seconds --create-dirs -o "$path" --fail else wget -q -O "$path" "$uri" --tries="$download_retries" fi return $? } function GetTempPathFileName { local path=$1 local temp_dir=$(GetTempDirectory) local temp_file_name=$(basename $path) echo $temp_dir$temp_file_name return 0 } function DownloadAndExtract { local uri=$1 local installDir=$2 local force=${3:-false} local download_retries=${4:-5} local retry_wait_time_seconds=${5:-30} local temp_tool_path=$(GetTempPathFileName $uri) echo "downloading to: $temp_tool_path" # Download file GetFile "$uri" "$temp_tool_path" $force $download_retries $retry_wait_time_seconds if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Failed to download '$uri' to '$temp_tool_path'." return 1 fi # Extract File echo "extracting from $temp_tool_path to $installDir" ExpandZip "$temp_tool_path" "$installDir" $force $download_retries $retry_wait_time_seconds if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Failed to extract '$temp_tool_path' to '$installDir'." return 1 fi return 0 } function NewScriptShim { local shimpath=$1 local tool_file_path=$2 local force=${3:-false} echo "Generating '$shimpath' shim" if [[ -f $shimpath ]]; then if [[ $force = false ]]; then echo "File '$shimpath' already exists." >&2 return 1 else rm -rf $shimpath fi fi if [[ ! -f $tool_file_path ]]; then # try to see if the path is lower cased tool_file_path="$(echo $tool_file_path | tr "[:upper:]" "[:lower:]")" if [[ ! -f $tool_file_path ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' "Specified tool file path:'$tool_file_path' does not exist" return 1 fi fi local shim_contents=$'#!/usr/bin/env bash\n' shim_contents+="SHIMARGS="$'$1\n' shim_contents+="$tool_file_path"$' $SHIMARGS\n' # Write shim file echo "$shim_contents" > $shimpath chmod +x $shimpath echo "Finished generating shim '$shimpath'" return $? }
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/post-build/sourcelink-validation.ps1
param( [Parameter(Mandatory=$true)][string] $InputPath, # Full path to directory where Symbols.NuGet packages to be checked are stored [Parameter(Mandatory=$true)][string] $ExtractPath, # Full path to directory where the packages will be extracted during validation [Parameter(Mandatory=$false)][string] $GHRepoName, # GitHub name of the repo including the Org. E.g., dotnet/arcade [Parameter(Mandatory=$false)][string] $GHCommit, # GitHub commit SHA used to build the packages [Parameter(Mandatory=$true)][string] $SourcelinkCliVersion # Version of SourceLink CLI to use ) . $PSScriptRoot\post-build-utils.ps1 # Cache/HashMap (File -> Exist flag) used to consult whether a file exist # in the repository at a specific commit point. This is populated by inserting # all files present in the repo at a specific commit point. $global:RepoFiles = @{} # Maximum number of jobs to run in parallel $MaxParallelJobs = 16 $MaxRetries = 5 # Wait time between check for system load $SecondsBetweenLoadChecks = 10 $ValidatePackage = { param( [string] $PackagePath # Full path to a Symbols.NuGet package ) . $using:PSScriptRoot\..\tools.ps1 # Ensure input file exist if (!(Test-Path $PackagePath)) { Write-Host "Input file does not exist: $PackagePath" return [pscustomobject]@{ result = 1 packagePath = $PackagePath } } # Extensions for which we'll look for SourceLink information # For now we'll only care about Portable & Embedded PDBs $RelevantExtensions = @('.dll', '.exe', '.pdb') Write-Host -NoNewLine 'Validating ' ([System.IO.Path]::GetFileName($PackagePath)) '...' $PackageId = [System.IO.Path]::GetFileNameWithoutExtension($PackagePath) $ExtractPath = Join-Path -Path $using:ExtractPath -ChildPath $PackageId $FailedFiles = 0 Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Directory]::CreateDirectory($ExtractPath) | Out-Null try { $zip = [System.IO.Compression.ZipFile]::OpenRead($PackagePath) $zip.Entries | Where-Object {$RelevantExtensions -contains [System.IO.Path]::GetExtension($_.Name)} | ForEach-Object { $FileName = $_.FullName $Extension = [System.IO.Path]::GetExtension($_.Name) $FakeName = -Join((New-Guid), $Extension) $TargetFile = Join-Path -Path $ExtractPath -ChildPath $FakeName # We ignore resource DLLs if ($FileName.EndsWith('.resources.dll')) { return [pscustomobject]@{ result = 0 packagePath = $PackagePath } } [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, $TargetFile, $true) $ValidateFile = { param( [string] $FullPath, # Full path to the module that has to be checked [string] $RealPath, [ref] $FailedFiles ) $sourcelinkExe = "$env:USERPROFILE\.dotnet\tools" $sourcelinkExe = Resolve-Path "$sourcelinkExe\sourcelink.exe" $SourceLinkInfos = & $sourcelinkExe print-urls $FullPath | Out-String if ($LASTEXITCODE -eq 0 -and -not ([string]::IsNullOrEmpty($SourceLinkInfos))) { $NumFailedLinks = 0 # We only care about Http addresses $Matches = (Select-String '(http[s]?)(:\/\/)([^\s,]+)' -Input $SourceLinkInfos -AllMatches).Matches if ($Matches.Count -ne 0) { $Matches.Value | ForEach-Object { $Link = $_ $CommitUrl = "https://raw.githubusercontent.com/${using:GHRepoName}/${using:GHCommit}/" $FilePath = $Link.Replace($CommitUrl, "") $Status = 200 $Cache = $using:RepoFiles $totalRetries = 0 while ($totalRetries -lt $using:MaxRetries) { if ( !($Cache.ContainsKey($FilePath)) ) { try { $Uri = $Link -as [System.URI] # Only GitHub links are valid if ($Uri.AbsoluteURI -ne $null -and ($Uri.Host -match 'github' -or $Uri.Host -match 'githubusercontent')) { $Status = (Invoke-WebRequest -Uri $Link -UseBasicParsing -Method HEAD -TimeoutSec 5).StatusCode } else { # If it's not a github link, we want to break out of the loop and not retry. $Status = 0 $totalRetries = $using:MaxRetries } } catch { Write-Host $_ $Status = 0 } } if ($Status -ne 200) { $totalRetries++ if ($totalRetries -ge $using:MaxRetries) { if ($NumFailedLinks -eq 0) { if ($FailedFiles.Value -eq 0) { Write-Host } Write-Host "`tFile $RealPath has broken links:" } Write-Host "`t`tFailed to retrieve $Link" $NumFailedLinks++ } } else { break } } } } if ($NumFailedLinks -ne 0) { $FailedFiles.value++ $global:LASTEXITCODE = 1 } } } &$ValidateFile $TargetFile $FileName ([ref]$FailedFiles) } } catch { Write-Host $_ } finally { $zip.Dispose() } if ($FailedFiles -eq 0) { Write-Host 'Passed.' return [pscustomobject]@{ result = 0 packagePath = $PackagePath } } else { Write-PipelineTelemetryError -Category 'SourceLink' -Message "$PackagePath has broken SourceLink links." return [pscustomobject]@{ result = 1 packagePath = $PackagePath } } } function CheckJobResult( $result, $packagePath, [ref]$ValidationFailures, [switch]$logErrors) { if ($result -ne '0') { if ($logErrors) { Write-PipelineTelemetryError -Category 'SourceLink' -Message "$packagePath has broken SourceLink links." } $ValidationFailures.Value++ } } function ValidateSourceLinkLinks { if ($GHRepoName -ne '' -and !($GHRepoName -Match '^[^\s\/]+/[^\s\/]+$')) { if (!($GHRepoName -Match '^[^\s-]+-[^\s]+$')) { Write-PipelineTelemetryError -Category 'SourceLink' -Message "GHRepoName should be in the format <org>/<repo> or <org>-<repo>. '$GHRepoName'" ExitWithExitCode 1 } else { $GHRepoName = $GHRepoName -replace '^([^\s-]+)-([^\s]+)$', '$1/$2'; } } if ($GHCommit -ne '' -and !($GHCommit -Match '^[0-9a-fA-F]{40}$')) { Write-PipelineTelemetryError -Category 'SourceLink' -Message "GHCommit should be a 40 chars hexadecimal string. '$GHCommit'" ExitWithExitCode 1 } if ($GHRepoName -ne '' -and $GHCommit -ne '') { $RepoTreeURL = -Join('http://api.github.com/repos/', $GHRepoName, '/git/trees/', $GHCommit, '?recursive=1') $CodeExtensions = @('.cs', '.vb', '.fs', '.fsi', '.fsx', '.fsscript') try { # Retrieve the list of files in the repo at that particular commit point and store them in the RepoFiles hash $Data = Invoke-WebRequest $RepoTreeURL -UseBasicParsing | ConvertFrom-Json | Select-Object -ExpandProperty tree foreach ($file in $Data) { $Extension = [System.IO.Path]::GetExtension($file.path) if ($CodeExtensions.Contains($Extension)) { $RepoFiles[$file.path] = 1 } } } catch { Write-Host "Problems downloading the list of files from the repo. Url used: $RepoTreeURL . Execution will proceed without caching." } } elseif ($GHRepoName -ne '' -or $GHCommit -ne '') { Write-Host 'For using the http caching mechanism both GHRepoName and GHCommit should be informed.' } if (Test-Path $ExtractPath) { Remove-Item $ExtractPath -Force -Recurse -ErrorAction SilentlyContinue } $ValidationFailures = 0 # Process each NuGet package in parallel Get-ChildItem "$InputPath\*.symbols.nupkg" | ForEach-Object { Write-Host "Starting $($_.FullName)" Start-Job -ScriptBlock $ValidatePackage -ArgumentList $_.FullName | Out-Null $NumJobs = @(Get-Job -State 'Running').Count while ($NumJobs -ge $MaxParallelJobs) { Write-Host "There are $NumJobs validation jobs running right now. Waiting $SecondsBetweenLoadChecks seconds to check again." sleep $SecondsBetweenLoadChecks $NumJobs = @(Get-Job -State 'Running').Count } foreach ($Job in @(Get-Job -State 'Completed')) { $jobResult = Wait-Job -Id $Job.Id | Receive-Job CheckJobResult $jobResult.result $jobResult.packagePath ([ref]$ValidationFailures) -LogErrors Remove-Job -Id $Job.Id } } foreach ($Job in @(Get-Job)) { $jobResult = Wait-Job -Id $Job.Id | Receive-Job CheckJobResult $jobResult.result $jobResult.packagePath ([ref]$ValidationFailures) Remove-Job -Id $Job.Id } if ($ValidationFailures -gt 0) { Write-PipelineTelemetryError -Category 'SourceLink' -Message "$ValidationFailures package(s) failed validation." ExitWithExitCode 1 } } function InstallSourcelinkCli { $sourcelinkCliPackageName = 'sourcelink' $dotnetRoot = InitializeDotNetCli -install:$true $dotnet = "$dotnetRoot\dotnet.exe" $toolList = & "$dotnet" tool list --global if (($toolList -like "*$sourcelinkCliPackageName*") -and ($toolList -like "*$sourcelinkCliVersion*")) { Write-Host "SourceLink CLI version $sourcelinkCliVersion is already installed." } else { Write-Host "Installing SourceLink CLI version $sourcelinkCliVersion..." Write-Host 'You may need to restart your command window if this is the first dotnet tool you have installed.' & "$dotnet" tool install $sourcelinkCliPackageName --version $sourcelinkCliVersion --verbosity "minimal" --global } } try { InstallSourcelinkCli foreach ($Job in @(Get-Job)) { Remove-Job -Id $Job.Id } ValidateSourceLinkLinks } catch { Write-Host $_.Exception Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'SourceLink' -Message $_ ExitWithExitCode 1 }
param( [Parameter(Mandatory=$true)][string] $InputPath, # Full path to directory where Symbols.NuGet packages to be checked are stored [Parameter(Mandatory=$true)][string] $ExtractPath, # Full path to directory where the packages will be extracted during validation [Parameter(Mandatory=$false)][string] $GHRepoName, # GitHub name of the repo including the Org. E.g., dotnet/arcade [Parameter(Mandatory=$false)][string] $GHCommit, # GitHub commit SHA used to build the packages [Parameter(Mandatory=$true)][string] $SourcelinkCliVersion # Version of SourceLink CLI to use ) . $PSScriptRoot\post-build-utils.ps1 # Cache/HashMap (File -> Exist flag) used to consult whether a file exist # in the repository at a specific commit point. This is populated by inserting # all files present in the repo at a specific commit point. $global:RepoFiles = @{} # Maximum number of jobs to run in parallel $MaxParallelJobs = 16 $MaxRetries = 5 $RetryWaitTimeInSeconds = 30 # Wait time between check for system load $SecondsBetweenLoadChecks = 10 $ValidatePackage = { param( [string] $PackagePath # Full path to a Symbols.NuGet package ) . $using:PSScriptRoot\..\tools.ps1 # Ensure input file exist if (!(Test-Path $PackagePath)) { Write-Host "Input file does not exist: $PackagePath" return [pscustomobject]@{ result = 1 packagePath = $PackagePath } } # Extensions for which we'll look for SourceLink information # For now we'll only care about Portable & Embedded PDBs $RelevantExtensions = @('.dll', '.exe', '.pdb') Write-Host -NoNewLine 'Validating ' ([System.IO.Path]::GetFileName($PackagePath)) '...' $PackageId = [System.IO.Path]::GetFileNameWithoutExtension($PackagePath) $ExtractPath = Join-Path -Path $using:ExtractPath -ChildPath $PackageId $FailedFiles = 0 Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Directory]::CreateDirectory($ExtractPath) | Out-Null try { $zip = [System.IO.Compression.ZipFile]::OpenRead($PackagePath) $zip.Entries | Where-Object {$RelevantExtensions -contains [System.IO.Path]::GetExtension($_.Name)} | ForEach-Object { $FileName = $_.FullName $Extension = [System.IO.Path]::GetExtension($_.Name) $FakeName = -Join((New-Guid), $Extension) $TargetFile = Join-Path -Path $ExtractPath -ChildPath $FakeName # We ignore resource DLLs if ($FileName.EndsWith('.resources.dll')) { return [pscustomobject]@{ result = 0 packagePath = $PackagePath } } [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, $TargetFile, $true) $ValidateFile = { param( [string] $FullPath, # Full path to the module that has to be checked [string] $RealPath, [ref] $FailedFiles ) $sourcelinkExe = "$env:USERPROFILE\.dotnet\tools" $sourcelinkExe = Resolve-Path "$sourcelinkExe\sourcelink.exe" $SourceLinkInfos = & $sourcelinkExe print-urls $FullPath | Out-String if ($LASTEXITCODE -eq 0 -and -not ([string]::IsNullOrEmpty($SourceLinkInfos))) { $NumFailedLinks = 0 # We only care about Http addresses $Matches = (Select-String '(http[s]?)(:\/\/)([^\s,]+)' -Input $SourceLinkInfos -AllMatches).Matches if ($Matches.Count -ne 0) { $Matches.Value | ForEach-Object { $Link = $_ $CommitUrl = "https://raw.githubusercontent.com/${using:GHRepoName}/${using:GHCommit}/" $FilePath = $Link.Replace($CommitUrl, "") $Status = 200 $Cache = $using:RepoFiles $attempts = 0 while ($attempts -lt $using:MaxRetries) { if ( !($Cache.ContainsKey($FilePath)) ) { try { $Uri = $Link -as [System.URI] if ($Link -match "submodules") { # Skip submodule links until sourcelink properly handles submodules $Status = 200 } elseif ($Uri.AbsoluteURI -ne $null -and ($Uri.Host -match 'github' -or $Uri.Host -match 'githubusercontent')) { # Only GitHub links are valid $Status = (Invoke-WebRequest -Uri $Link -UseBasicParsing -Method HEAD -TimeoutSec 5).StatusCode } else { # If it's not a github link, we want to break out of the loop and not retry. $Status = 0 $attempts = $using:MaxRetries } } catch { Write-Host $_ $Status = 0 } } if ($Status -ne 200) { $attempts++ if ($attempts -lt $using:MaxRetries) { $attemptsLeft = $using:MaxRetries - $attempts Write-Warning "Download failed, $attemptsLeft attempts remaining, will retry in $using:RetryWaitTimeInSeconds seconds" Start-Sleep -Seconds $using:RetryWaitTimeInSeconds } else { if ($NumFailedLinks -eq 0) { if ($FailedFiles.Value -eq 0) { Write-Host } Write-Host "`tFile $RealPath has broken links:" } Write-Host "`t`tFailed to retrieve $Link" $NumFailedLinks++ } } else { break } } } } if ($NumFailedLinks -ne 0) { $FailedFiles.value++ $global:LASTEXITCODE = 1 } } } &$ValidateFile $TargetFile $FileName ([ref]$FailedFiles) } } catch { Write-Host $_ } finally { $zip.Dispose() } if ($FailedFiles -eq 0) { Write-Host 'Passed.' return [pscustomobject]@{ result = 0 packagePath = $PackagePath } } else { Write-PipelineTelemetryError -Category 'SourceLink' -Message "$PackagePath has broken SourceLink links." return [pscustomobject]@{ result = 1 packagePath = $PackagePath } } } function CheckJobResult( $result, $packagePath, [ref]$ValidationFailures, [switch]$logErrors) { if ($result -ne '0') { if ($logErrors) { Write-PipelineTelemetryError -Category 'SourceLink' -Message "$packagePath has broken SourceLink links." } $ValidationFailures.Value++ } } function ValidateSourceLinkLinks { if ($GHRepoName -ne '' -and !($GHRepoName -Match '^[^\s\/]+/[^\s\/]+$')) { if (!($GHRepoName -Match '^[^\s-]+-[^\s]+$')) { Write-PipelineTelemetryError -Category 'SourceLink' -Message "GHRepoName should be in the format <org>/<repo> or <org>-<repo>. '$GHRepoName'" ExitWithExitCode 1 } else { $GHRepoName = $GHRepoName -replace '^([^\s-]+)-([^\s]+)$', '$1/$2'; } } if ($GHCommit -ne '' -and !($GHCommit -Match '^[0-9a-fA-F]{40}$')) { Write-PipelineTelemetryError -Category 'SourceLink' -Message "GHCommit should be a 40 chars hexadecimal string. '$GHCommit'" ExitWithExitCode 1 } if ($GHRepoName -ne '' -and $GHCommit -ne '') { $RepoTreeURL = -Join('http://api.github.com/repos/', $GHRepoName, '/git/trees/', $GHCommit, '?recursive=1') $CodeExtensions = @('.cs', '.vb', '.fs', '.fsi', '.fsx', '.fsscript') try { # Retrieve the list of files in the repo at that particular commit point and store them in the RepoFiles hash $Data = Invoke-WebRequest $RepoTreeURL -UseBasicParsing | ConvertFrom-Json | Select-Object -ExpandProperty tree foreach ($file in $Data) { $Extension = [System.IO.Path]::GetExtension($file.path) if ($CodeExtensions.Contains($Extension)) { $RepoFiles[$file.path] = 1 } } } catch { Write-Host "Problems downloading the list of files from the repo. Url used: $RepoTreeURL . Execution will proceed without caching." } } elseif ($GHRepoName -ne '' -or $GHCommit -ne '') { Write-Host 'For using the http caching mechanism both GHRepoName and GHCommit should be informed.' } if (Test-Path $ExtractPath) { Remove-Item $ExtractPath -Force -Recurse -ErrorAction SilentlyContinue } $ValidationFailures = 0 # Process each NuGet package in parallel Get-ChildItem "$InputPath\*.symbols.nupkg" | ForEach-Object { Write-Host "Starting $($_.FullName)" Start-Job -ScriptBlock $ValidatePackage -ArgumentList $_.FullName | Out-Null $NumJobs = @(Get-Job -State 'Running').Count while ($NumJobs -ge $MaxParallelJobs) { Write-Host "There are $NumJobs validation jobs running right now. Waiting $SecondsBetweenLoadChecks seconds to check again." sleep $SecondsBetweenLoadChecks $NumJobs = @(Get-Job -State 'Running').Count } foreach ($Job in @(Get-Job -State 'Completed')) { $jobResult = Wait-Job -Id $Job.Id | Receive-Job CheckJobResult $jobResult.result $jobResult.packagePath ([ref]$ValidationFailures) -LogErrors Remove-Job -Id $Job.Id } } foreach ($Job in @(Get-Job)) { $jobResult = Wait-Job -Id $Job.Id | Receive-Job CheckJobResult $jobResult.result $jobResult.packagePath ([ref]$ValidationFailures) Remove-Job -Id $Job.Id } if ($ValidationFailures -gt 0) { Write-PipelineTelemetryError -Category 'SourceLink' -Message "$ValidationFailures package(s) failed validation." ExitWithExitCode 1 } } function InstallSourcelinkCli { $sourcelinkCliPackageName = 'sourcelink' $dotnetRoot = InitializeDotNetCli -install:$true $dotnet = "$dotnetRoot\dotnet.exe" $toolList = & "$dotnet" tool list --global if (($toolList -like "*$sourcelinkCliPackageName*") -and ($toolList -like "*$sourcelinkCliVersion*")) { Write-Host "SourceLink CLI version $sourcelinkCliVersion is already installed." } else { Write-Host "Installing SourceLink CLI version $sourcelinkCliVersion..." Write-Host 'You may need to restart your command window if this is the first dotnet tool you have installed.' & "$dotnet" tool install $sourcelinkCliPackageName --version $sourcelinkCliVersion --verbosity "minimal" --global } } try { InstallSourcelinkCli foreach ($Job in @(Get-Job)) { Remove-Job -Id $Job.Id } ValidateSourceLinkLinks } catch { Write-Host $_.Exception Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'SourceLink' -Message $_ ExitWithExitCode 1 }
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/sdk-task.ps1
[CmdletBinding(PositionalBinding=$false)] Param( [string] $configuration = 'Debug', [string] $task, [string] $verbosity = 'minimal', [string] $msbuildEngine = $null, [switch] $restore, [switch] $prepareMachine, [switch] $help, [Parameter(ValueFromRemainingArguments=$true)][String[]]$properties ) $ci = $true $binaryLog = $true $warnAsError = $true . $PSScriptRoot\tools.ps1 function Print-Usage() { Write-Host "Common settings:" Write-Host " -task <value> Name of Arcade task (name of a project in SdkTasks directory of the Arcade SDK package)" Write-Host " -restore Restore dependencies" Write-Host " -verbosity <value> Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic]" Write-Host " -help Print help and exit" Write-Host "" Write-Host "Advanced settings:" Write-Host " -prepareMachine Prepare machine for CI run" Write-Host " -msbuildEngine <value> Msbuild engine to use to run build ('dotnet', 'vs', or unspecified)." Write-Host "" Write-Host "Command line arguments not listed above are passed thru to msbuild." } function Build([string]$target) { $logSuffix = if ($target -eq 'Execute') { '' } else { ".$target" } $log = Join-Path $LogDir "$task$logSuffix.binlog" $outputPath = Join-Path $ToolsetDir "$task\" MSBuild $taskProject ` /bl:$log ` /t:$target ` /p:Configuration=$configuration ` /p:RepoRoot=$RepoRoot ` /p:BaseIntermediateOutputPath=$outputPath ` /v:$verbosity ` @properties } try { if ($help -or (($null -ne $properties) -and ($properties.Contains('/help') -or $properties.Contains('/?')))) { Print-Usage exit 0 } if ($task -eq "") { Write-PipelineTelemetryError -Category 'Build' -Message "Missing required parameter '-task <value>'" Print-Usage ExitWithExitCode 1 } if( $msbuildEngine -eq "vs") { # Ensure desktop MSBuild is available for sdk tasks. if( -not ($GlobalJson.tools.PSObject.Properties.Name -contains "vs" )) { $GlobalJson.tools | Add-Member -Name "vs" -Value (ConvertFrom-Json "{ `"version`": `"16.5`" }") -MemberType NoteProperty } if( -not ($GlobalJson.tools.PSObject.Properties.Name -match "xcopy-msbuild" )) { $GlobalJson.tools | Add-Member -Name "xcopy-msbuild" -Value "16.10.0-preview2" -MemberType NoteProperty } if ($GlobalJson.tools."xcopy-msbuild".Trim() -ine "none") { $xcopyMSBuildToolsFolder = InitializeXCopyMSBuild $GlobalJson.tools."xcopy-msbuild" -install $true } if ($xcopyMSBuildToolsFolder -eq $null) { throw 'Unable to get xcopy downloadable version of msbuild' } $global:_MSBuildExe = "$($xcopyMSBuildToolsFolder)\MSBuild\Current\Bin\MSBuild.exe" } $taskProject = GetSdkTaskProject $task if (!(Test-Path $taskProject)) { Write-PipelineTelemetryError -Category 'Build' -Message "Unknown task: $task" ExitWithExitCode 1 } if ($restore) { Build 'Restore' } Build 'Execute' } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'Build' -Message $_ ExitWithExitCode 1 } ExitWithExitCode 0
[CmdletBinding(PositionalBinding=$false)] Param( [string] $configuration = 'Debug', [string] $task, [string] $verbosity = 'minimal', [string] $msbuildEngine = $null, [switch] $restore, [switch] $prepareMachine, [switch] $help, [Parameter(ValueFromRemainingArguments=$true)][String[]]$properties ) $ci = $true $binaryLog = $true $warnAsError = $true . $PSScriptRoot\tools.ps1 function Print-Usage() { Write-Host "Common settings:" Write-Host " -task <value> Name of Arcade task (name of a project in SdkTasks directory of the Arcade SDK package)" Write-Host " -restore Restore dependencies" Write-Host " -verbosity <value> Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic]" Write-Host " -help Print help and exit" Write-Host "" Write-Host "Advanced settings:" Write-Host " -prepareMachine Prepare machine for CI run" Write-Host " -msbuildEngine <value> Msbuild engine to use to run build ('dotnet', 'vs', or unspecified)." Write-Host "" Write-Host "Command line arguments not listed above are passed thru to msbuild." } function Build([string]$target) { $logSuffix = if ($target -eq 'Execute') { '' } else { ".$target" } $log = Join-Path $LogDir "$task$logSuffix.binlog" $outputPath = Join-Path $ToolsetDir "$task\" MSBuild $taskProject ` /bl:$log ` /t:$target ` /p:Configuration=$configuration ` /p:RepoRoot=$RepoRoot ` /p:BaseIntermediateOutputPath=$outputPath ` /v:$verbosity ` @properties } try { if ($help -or (($null -ne $properties) -and ($properties.Contains('/help') -or $properties.Contains('/?')))) { Print-Usage exit 0 } if ($task -eq "") { Write-PipelineTelemetryError -Category 'Build' -Message "Missing required parameter '-task <value>'" Print-Usage ExitWithExitCode 1 } if( $msbuildEngine -eq "vs") { # Ensure desktop MSBuild is available for sdk tasks. if( -not ($GlobalJson.tools.PSObject.Properties.Name -contains "vs" )) { $GlobalJson.tools | Add-Member -Name "vs" -Value (ConvertFrom-Json "{ `"version`": `"16.5`" }") -MemberType NoteProperty } if( -not ($GlobalJson.tools.PSObject.Properties.Name -match "xcopy-msbuild" )) { $GlobalJson.tools | Add-Member -Name "xcopy-msbuild" -Value "16.10.0-preview2" -MemberType NoteProperty } if ($GlobalJson.tools."xcopy-msbuild".Trim() -ine "none") { $xcopyMSBuildToolsFolder = InitializeXCopyMSBuild $GlobalJson.tools."xcopy-msbuild" -install $true } if ($xcopyMSBuildToolsFolder -eq $null) { throw 'Unable to get xcopy downloadable version of msbuild' } $global:_MSBuildExe = "$($xcopyMSBuildToolsFolder)\MSBuild\Current\Bin\MSBuild.exe" } $taskProject = GetSdkTaskProject $task if (!(Test-Path $taskProject)) { Write-PipelineTelemetryError -Category 'Build' -Message "Unknown task: $task" ExitWithExitCode 1 } if ($restore) { if ($ci) { Try-LogClientIpAddress } Build 'Restore' } Build 'Execute' } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'Build' -Message $_ ExitWithExitCode 1 } ExitWithExitCode 0
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/templates/job/job.yml
# Internal resources (telemetry, microbuild) can only be accessed from non-public projects, # and some (Microbuild) should only be applied to non-PR cases for internal builds. parameters: # Job schema parameters - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job cancelTimeoutInMinutes: '' condition: '' container: '' continueOnError: false dependsOn: '' displayName: '' pool: '' steps: [] strategy: '' timeoutInMinutes: '' variables: [] workspace: '' # Job base template specific parameters # See schema documentation - https://github.com/dotnet/arcade/blob/master/Documentation/AzureDevOps/TemplateSchema.md artifacts: '' enableMicrobuild: false enablePublishBuildArtifacts: false enablePublishBuildAssets: false enablePublishTestResults: false enablePublishUsingPipelines: false mergeTestResults: false testRunTitle: '' testResultsFormat: '' name: '' preSteps: [] runAsPublic: false jobs: - job: ${{ parameters.name }} ${{ if ne(parameters.cancelTimeoutInMinutes, '') }}: cancelTimeoutInMinutes: ${{ parameters.cancelTimeoutInMinutes }} ${{ if ne(parameters.condition, '') }}: condition: ${{ parameters.condition }} ${{ if ne(parameters.container, '') }}: container: ${{ parameters.container }} ${{ if ne(parameters.continueOnError, '') }}: continueOnError: ${{ parameters.continueOnError }} ${{ if ne(parameters.dependsOn, '') }}: dependsOn: ${{ parameters.dependsOn }} ${{ if ne(parameters.displayName, '') }}: displayName: ${{ parameters.displayName }} ${{ if ne(parameters.pool, '') }}: pool: ${{ parameters.pool }} ${{ if ne(parameters.strategy, '') }}: strategy: ${{ parameters.strategy }} ${{ if ne(parameters.timeoutInMinutes, '') }}: timeoutInMinutes: ${{ parameters.timeoutInMinutes }} variables: - ${{ if ne(parameters.enableTelemetry, 'false') }}: - name: DOTNET_CLI_TELEMETRY_PROFILE value: '$(Build.Repository.Uri)' - ${{ if eq(parameters.enableRichCodeNavigation, 'true') }}: - name: EnableRichCodeNavigation value: 'true' - ${{ each variable in parameters.variables }}: # handle name-value variable syntax # example: # - name: [key] # value: [value] - ${{ if ne(variable.name, '') }}: - name: ${{ variable.name }} value: ${{ variable.value }} # handle variable groups - ${{ if ne(variable.group, '') }}: - group: ${{ variable.group }} # handle key-value variable syntax. # example: # - [key]: [value] - ${{ if and(eq(variable.name, ''), eq(variable.group, '')) }}: - ${{ each pair in variable }}: - name: ${{ pair.key }} value: ${{ pair.value }} # DotNet-HelixApi-Access provides 'HelixApiAccessToken' for internal builds - ${{ if and(eq(parameters.enableTelemetry, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - group: DotNet-HelixApi-Access ${{ if ne(parameters.workspace, '') }}: workspace: ${{ parameters.workspace }} steps: - ${{ if ne(parameters.preSteps, '') }}: - ${{ each preStep in parameters.preSteps }}: - ${{ preStep }} - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - task: MicroBuildSigningPlugin@2 displayName: Install MicroBuild plugin inputs: signType: $(_SignType) zipSources: false feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json env: TeamName: $(_TeamName) continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) - task: NuGetAuthenticate@0 - ${{ if or(eq(parameters.artifacts.download, 'true'), ne(parameters.artifacts.download, '')) }}: - task: DownloadPipelineArtifact@2 inputs: buildType: current artifactName: ${{ coalesce(parameters.artifacts.download.name, 'Artifacts_$(Agent.OS)_$(_BuildConfig)') }} targetPath: ${{ coalesce(parameters.artifacts.download.path, 'artifacts') }} itemPattern: ${{ coalesce(parameters.artifacts.download.pattern, '**') }} - ${{ each step in parameters.steps }}: - ${{ step }} - ${{ if eq(parameters.enableRichCodeNavigation, true) }}: - task: RichCodeNavIndexer@0 displayName: RichCodeNav Upload inputs: languages: ${{ coalesce(parameters.richCodeNavigationLanguage, 'csharp') }} environment: ${{ coalesce(parameters.richCodeNavigationEnvironment, 'production') }} richNavLogOutputDirectory: $(Build.SourcesDirectory)/artifacts/bin continueOnError: true - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: MicroBuildCleanup@1 displayName: Execute Microbuild cleanup tasks condition: and(always(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) continueOnError: ${{ parameters.continueOnError }} env: TeamName: $(_TeamName) - ${{ if ne(parameters.artifacts.publish, '') }}: - ${{ if or(eq(parameters.artifacts.publish.artifacts, 'true'), ne(parameters.artifacts.publish.artifacts, '')) }}: - task: CopyFiles@2 displayName: Gather binaries for publish to artifacts inputs: SourceFolder: 'artifacts/bin' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/bin' - task: CopyFiles@2 displayName: Gather packages for publish to artifacts inputs: SourceFolder: 'artifacts/packages' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/packages' - task: PublishBuildArtifacts@1 displayName: Publish pipeline artifacts inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/artifacts' PublishLocation: Container ArtifactName: ${{ coalesce(parameters.artifacts.publish.artifacts.name , 'Artifacts_$(Agent.Os)_$(_BuildConfig)') }} continueOnError: true condition: always() - ${{ if or(eq(parameters.artifacts.publish.logs, 'true'), ne(parameters.artifacts.publish.logs, '')) }}: - publish: artifacts/log artifact: ${{ coalesce(parameters.artifacts.publish.logs.name, 'Logs_Build_$(Agent.Os)_$(_BuildConfig)') }} displayName: Publish logs continueOnError: true condition: always() - ${{ if or(eq(parameters.artifacts.publish.manifests, 'true'), ne(parameters.artifacts.publish.manifests, '')) }}: - ${{ if and(ne(parameters.enablePublishUsingPipelines, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: CopyFiles@2 displayName: Gather Asset Manifests inputs: SourceFolder: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/AssetManifest' TargetFolder: '$(Build.ArtifactStagingDirectory)/AssetManifests' continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - task: PublishBuildArtifacts@1 displayName: Push Asset Manifests inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/AssetManifests' PublishLocation: Container ArtifactName: AssetManifests continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - ${{ if ne(parameters.enablePublishBuildArtifacts, 'false') }}: - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)' PublishLocation: Container ArtifactName: ${{ coalesce(parameters.enablePublishBuildArtifacts.artifactName, '$(Agent.Os)_$(Agent.JobName)' ) }} continueOnError: true condition: always() - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'xunit')) }}: - task: PublishTestResults@2 displayName: Publish XUnit Test Results inputs: testResultsFormat: 'xUnit' testResultsFiles: '*.xml' searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-xunit mergeTestResults: ${{ parameters.mergeTestResults }} continueOnError: true condition: always() - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'vstest')) }}: - task: PublishTestResults@2 displayName: Publish TRX Test Results inputs: testResultsFormat: 'VSTest' testResultsFiles: '*.trx' searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-trx mergeTestResults: ${{ parameters.mergeTestResults }} continueOnError: true condition: always() - ${{ if and(eq(parameters.enablePublishBuildAssets, true), ne(parameters.enablePublishUsingPipelines, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: CopyFiles@2 displayName: Gather Asset Manifests inputs: SourceFolder: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/AssetManifest' TargetFolder: '$(Build.StagingDirectory)/AssetManifests' continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - task: PublishBuildArtifacts@1 displayName: Push Asset Manifests inputs: PathtoPublish: '$(Build.StagingDirectory)/AssetManifests' PublishLocation: Container ArtifactName: AssetManifests continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true'))
# Internal resources (telemetry, microbuild) can only be accessed from non-public projects, # and some (Microbuild) should only be applied to non-PR cases for internal builds. parameters: # Job schema parameters - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job cancelTimeoutInMinutes: '' condition: '' container: '' continueOnError: false dependsOn: '' displayName: '' pool: '' steps: [] strategy: '' timeoutInMinutes: '' variables: [] workspace: '' # Job base template specific parameters # See schema documentation - https://github.com/dotnet/arcade/blob/master/Documentation/AzureDevOps/TemplateSchema.md artifacts: '' enableMicrobuild: false enablePublishBuildArtifacts: false enablePublishBuildAssets: false enablePublishTestResults: false enablePublishUsingPipelines: false mergeTestResults: false testRunTitle: '' testResultsFormat: '' name: '' preSteps: [] runAsPublic: false jobs: - job: ${{ parameters.name }} ${{ if ne(parameters.cancelTimeoutInMinutes, '') }}: cancelTimeoutInMinutes: ${{ parameters.cancelTimeoutInMinutes }} ${{ if ne(parameters.condition, '') }}: condition: ${{ parameters.condition }} ${{ if ne(parameters.container, '') }}: container: ${{ parameters.container }} ${{ if ne(parameters.continueOnError, '') }}: continueOnError: ${{ parameters.continueOnError }} ${{ if ne(parameters.dependsOn, '') }}: dependsOn: ${{ parameters.dependsOn }} ${{ if ne(parameters.displayName, '') }}: displayName: ${{ parameters.displayName }} ${{ if ne(parameters.pool, '') }}: pool: ${{ parameters.pool }} ${{ if ne(parameters.strategy, '') }}: strategy: ${{ parameters.strategy }} ${{ if ne(parameters.timeoutInMinutes, '') }}: timeoutInMinutes: ${{ parameters.timeoutInMinutes }} variables: - ${{ if ne(parameters.enableTelemetry, 'false') }}: - name: DOTNET_CLI_TELEMETRY_PROFILE value: '$(Build.Repository.Uri)' - ${{ if eq(parameters.enableRichCodeNavigation, 'true') }}: - name: EnableRichCodeNavigation value: 'true' - ${{ each variable in parameters.variables }}: # handle name-value variable syntax # example: # - name: [key] # value: [value] - ${{ if ne(variable.name, '') }}: - name: ${{ variable.name }} value: ${{ variable.value }} # handle variable groups - ${{ if ne(variable.group, '') }}: - group: ${{ variable.group }} # handle key-value variable syntax. # example: # - [key]: [value] - ${{ if and(eq(variable.name, ''), eq(variable.group, '')) }}: - ${{ each pair in variable }}: - name: ${{ pair.key }} value: ${{ pair.value }} # DotNet-HelixApi-Access provides 'HelixApiAccessToken' for internal builds - ${{ if and(eq(parameters.enableTelemetry, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - group: DotNet-HelixApi-Access ${{ if ne(parameters.workspace, '') }}: workspace: ${{ parameters.workspace }} steps: - ${{ if ne(parameters.preSteps, '') }}: - ${{ each preStep in parameters.preSteps }}: - ${{ preStep }} - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - task: MicroBuildSigningPlugin@3 displayName: Install MicroBuild plugin inputs: signType: $(_SignType) zipSources: false feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json env: TeamName: $(_TeamName) continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) - task: NuGetAuthenticate@0 - ${{ if or(eq(parameters.artifacts.download, 'true'), ne(parameters.artifacts.download, '')) }}: - task: DownloadPipelineArtifact@2 inputs: buildType: current artifactName: ${{ coalesce(parameters.artifacts.download.name, 'Artifacts_$(Agent.OS)_$(_BuildConfig)') }} targetPath: ${{ coalesce(parameters.artifacts.download.path, 'artifacts') }} itemPattern: ${{ coalesce(parameters.artifacts.download.pattern, '**') }} - ${{ each step in parameters.steps }}: - ${{ step }} - ${{ if eq(parameters.enableRichCodeNavigation, true) }}: - task: RichCodeNavIndexer@0 displayName: RichCodeNav Upload inputs: languages: ${{ coalesce(parameters.richCodeNavigationLanguage, 'csharp') }} environment: ${{ coalesce(parameters.richCodeNavigationEnvironment, 'production') }} richNavLogOutputDirectory: $(Build.SourcesDirectory)/artifacts/bin continueOnError: true - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: MicroBuildCleanup@1 displayName: Execute Microbuild cleanup tasks condition: and(always(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) continueOnError: ${{ parameters.continueOnError }} env: TeamName: $(_TeamName) - ${{ if ne(parameters.artifacts.publish, '') }}: - ${{ if or(eq(parameters.artifacts.publish.artifacts, 'true'), ne(parameters.artifacts.publish.artifacts, '')) }}: - task: CopyFiles@2 displayName: Gather binaries for publish to artifacts inputs: SourceFolder: 'artifacts/bin' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/bin' - task: CopyFiles@2 displayName: Gather packages for publish to artifacts inputs: SourceFolder: 'artifacts/packages' Contents: '**' TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/packages' - task: PublishBuildArtifacts@1 displayName: Publish pipeline artifacts inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/artifacts' PublishLocation: Container ArtifactName: ${{ coalesce(parameters.artifacts.publish.artifacts.name , 'Artifacts_$(Agent.Os)_$(_BuildConfig)') }} continueOnError: true condition: always() - ${{ if or(eq(parameters.artifacts.publish.logs, 'true'), ne(parameters.artifacts.publish.logs, '')) }}: - publish: artifacts/log artifact: ${{ coalesce(parameters.artifacts.publish.logs.name, 'Logs_Build_$(Agent.Os)_$(_BuildConfig)') }} displayName: Publish logs continueOnError: true condition: always() - ${{ if or(eq(parameters.artifacts.publish.manifests, 'true'), ne(parameters.artifacts.publish.manifests, '')) }}: - ${{ if and(ne(parameters.enablePublishUsingPipelines, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: CopyFiles@2 displayName: Gather Asset Manifests inputs: SourceFolder: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/AssetManifest' TargetFolder: '$(Build.ArtifactStagingDirectory)/AssetManifests' continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - task: PublishBuildArtifacts@1 displayName: Push Asset Manifests inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/AssetManifests' PublishLocation: Container ArtifactName: AssetManifests continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - ${{ if ne(parameters.enablePublishBuildArtifacts, 'false') }}: - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)' PublishLocation: Container ArtifactName: ${{ coalesce(parameters.enablePublishBuildArtifacts.artifactName, '$(Agent.Os)_$(Agent.JobName)' ) }} continueOnError: true condition: always() - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'xunit')) }}: - task: PublishTestResults@2 displayName: Publish XUnit Test Results inputs: testResultsFormat: 'xUnit' testResultsFiles: '*.xml' searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-xunit mergeTestResults: ${{ parameters.mergeTestResults }} continueOnError: true condition: always() - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'vstest')) }}: - task: PublishTestResults@2 displayName: Publish TRX Test Results inputs: testResultsFormat: 'VSTest' testResultsFiles: '*.trx' searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-trx mergeTestResults: ${{ parameters.mergeTestResults }} continueOnError: true condition: always() - ${{ if and(eq(parameters.enablePublishBuildAssets, true), ne(parameters.enablePublishUsingPipelines, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: CopyFiles@2 displayName: Gather Asset Manifests inputs: SourceFolder: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/AssetManifest' TargetFolder: '$(Build.StagingDirectory)/AssetManifests' continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) - task: PublishBuildArtifacts@1 displayName: Push Asset Manifests inputs: PathtoPublish: '$(Build.StagingDirectory)/AssetManifests' PublishLocation: Container ArtifactName: AssetManifests continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true'))
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/templates/job/source-index-stage1.yml
parameters: runAsPublic: false sourceIndexPackageVersion: 1.0.1-20210614.1 sourceIndexPackageSource: https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json sourceIndexBuildCommand: powershell -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "eng/common/build.ps1 -restore -build -binarylog -ci" preSteps: [] binlogPath: artifacts/log/Debug/Build.binlog pool: vmImage: vs2017-win2016 condition: '' dependsOn: '' jobs: - job: SourceIndexStage1 dependsOn: ${{ parameters.dependsOn }} condition: ${{ parameters.condition }} variables: - name: SourceIndexPackageVersion value: ${{ parameters.sourceIndexPackageVersion }} - name: SourceIndexPackageSource value: ${{ parameters.sourceIndexPackageSource }} - name: BinlogPath value: ${{ parameters.binlogPath }} - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - group: source-dot-net stage1 variables pool: ${{ parameters.pool }} steps: - ${{ each preStep in parameters.preSteps }}: - ${{ preStep }} - task: UseDotNet@2 displayName: Use .NET Core sdk 3.1 inputs: packageType: sdk version: 3.1.x - task: UseDotNet@2 displayName: Use .NET Core sdk inputs: useGlobalJson: true - script: | dotnet tool install BinLogToSln --version $(SourceIndexPackageVersion) --add-source $(SourceIndexPackageSource) --tool-path .source-index/tools dotnet tool install UploadIndexStage1 --version $(SourceIndexPackageVersion) --add-source $(SourceIndexPackageSource) --tool-path .source-index/tools echo ##vso[task.prependpath]$(Build.SourcesDirectory)/.source-index/tools displayName: Download Tools - script: ${{ parameters.sourceIndexBuildCommand }} displayName: Build Repository - script: BinLogToSln -i $(BinlogPath) -r $(Build.SourcesDirectory) -n $(Build.Repository.Name) -o .source-index/stage1output displayName: Process Binlog into indexable sln env: DOTNET_ROLL_FORWARD_ON_NO_CANDIDATE_FX: 2 - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - script: UploadIndexStage1 -i .source-index/stage1output -n $(Build.Repository.Name) displayName: Upload stage1 artifacts to source index env: BLOB_CONTAINER_URL: $(source-dot-net-stage1-blob-container-url) DOTNET_ROLL_FORWARD_ON_NO_CANDIDATE_FX: 2
parameters: runAsPublic: false sourceIndexPackageVersion: 1.0.1-20210614.1 sourceIndexPackageSource: https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json sourceIndexBuildCommand: powershell -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "eng/common/build.ps1 -restore -build -binarylog -ci" preSteps: [] binlogPath: artifacts/log/Debug/Build.binlog pool: vmImage: vs2017-win2016 condition: '' dependsOn: '' jobs: - job: SourceIndexStage1 dependsOn: ${{ parameters.dependsOn }} condition: ${{ parameters.condition }} variables: - name: SourceIndexPackageVersion value: ${{ parameters.sourceIndexPackageVersion }} - name: SourceIndexPackageSource value: ${{ parameters.sourceIndexPackageSource }} - name: BinlogPath value: ${{ parameters.binlogPath }} - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - group: source-dot-net stage1 variables pool: ${{ parameters.pool }} steps: - ${{ each preStep in parameters.preSteps }}: - ${{ preStep }} - task: UseDotNet@2 displayName: Use .NET Core sdk 3.1 inputs: packageType: sdk version: 3.1.x installationPath: $(Agent.TempDirectory)/dotnet workingDirectory: $(Agent.TempDirectory) - script: | $(Agent.TempDirectory)/dotnet/dotnet tool install BinLogToSln --version $(SourceIndexPackageVersion) --add-source $(SourceIndexPackageSource) --tool-path $(Agent.TempDirectory)/.source-index/tools $(Agent.TempDirectory)/dotnet/dotnet tool install UploadIndexStage1 --version $(SourceIndexPackageVersion) --add-source $(SourceIndexPackageSource) --tool-path $(Agent.TempDirectory)/.source-index/tools displayName: Download Tools # Set working directory to temp directory so 'dotnet' doesn't try to use global.json and use the repo's sdk. workingDirectory: $(Agent.TempDirectory) - script: ${{ parameters.sourceIndexBuildCommand }} displayName: Build Repository - script: $(Agent.TempDirectory)/.source-index/tools/BinLogToSln -i $(BinlogPath) -r $(Build.SourcesDirectory) -n $(Build.Repository.Name) -o .source-index/stage1output displayName: Process Binlog into indexable sln - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - script: $(Agent.TempDirectory)/.source-index/tools/UploadIndexStage1 -i .source-index/stage1output -n $(Build.Repository.Name) displayName: Upload stage1 artifacts to source index env: BLOB_CONTAINER_URL: $(source-dot-net-stage1-blob-container-url)
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/tools.ps1
# Initialize variables if they aren't already defined. # These may be defined as parameters of the importing script, or set after importing this script. # CI mode - set to true on CI server for PR validation build or official build. [bool]$ci = if (Test-Path variable:ci) { $ci } else { $false } # Build configuration. Common values include 'Debug' and 'Release', but the repository may use other names. [string]$configuration = if (Test-Path variable:configuration) { $configuration } else { 'Debug' } # Set to true to opt out of outputting binary log while running in CI [bool]$excludeCIBinarylog = if (Test-Path variable:excludeCIBinarylog) { $excludeCIBinarylog } else { $false } # Set to true to output binary log from msbuild. Note that emitting binary log slows down the build. [bool]$binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $ci -and !$excludeCIBinarylog } # Set to true to use the pipelines logger which will enable Azure logging output. # https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md # This flag is meant as a temporary opt-opt for the feature while validate it across # our consumers. It will be deleted in the future. [bool]$pipelinesLog = if (Test-Path variable:pipelinesLog) { $pipelinesLog } else { $ci } # Turns on machine preparation/clean up code that changes the machine state (e.g. kills build processes). [bool]$prepareMachine = if (Test-Path variable:prepareMachine) { $prepareMachine } else { $false } # True to restore toolsets and dependencies. [bool]$restore = if (Test-Path variable:restore) { $restore } else { $true } # Adjusts msbuild verbosity level. [string]$verbosity = if (Test-Path variable:verbosity) { $verbosity } else { 'minimal' } # Set to true to reuse msbuild nodes. Recommended to not reuse on CI. [bool]$nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { !$ci } # Configures warning treatment in msbuild. [bool]$warnAsError = if (Test-Path variable:warnAsError) { $warnAsError } else { $true } # Specifies which msbuild engine to use for build: 'vs', 'dotnet' or unspecified (determined based on presence of tools.vs in global.json). [string]$msbuildEngine = if (Test-Path variable:msbuildEngine) { $msbuildEngine } else { $null } # True to attempt using .NET Core already that meets requirements specified in global.json # installed on the machine instead of downloading one. [bool]$useInstalledDotNetCli = if (Test-Path variable:useInstalledDotNetCli) { $useInstalledDotNetCli } else { $true } # Enable repos to use a particular version of the on-line dotnet-install scripts. # default URL: https://dotnet.microsoft.com/download/dotnet/scripts/v1/dotnet-install.ps1 [string]$dotnetInstallScriptVersion = if (Test-Path variable:dotnetInstallScriptVersion) { $dotnetInstallScriptVersion } else { 'v1' } # True to use global NuGet cache instead of restoring packages to repository-local directory. [bool]$useGlobalNuGetCache = if (Test-Path variable:useGlobalNuGetCache) { $useGlobalNuGetCache } else { !$ci } # True to exclude prerelease versions Visual Studio during build [bool]$excludePrereleaseVS = if (Test-Path variable:excludePrereleaseVS) { $excludePrereleaseVS } else { $false } # An array of names of processes to stop on script exit if prepareMachine is true. $processesToStopOnExit = if (Test-Path variable:processesToStopOnExit) { $processesToStopOnExit } else { @('msbuild', 'dotnet', 'vbcscompiler') } $disableConfigureToolsetImport = if (Test-Path variable:disableConfigureToolsetImport) { $disableConfigureToolsetImport } else { $null } set-strictmode -version 2.0 $ErrorActionPreference = 'Stop' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # If specifies, provides an alternate path for getting .NET Core SDKs and Runtimes. This script will still try public sources first. [string]$runtimeSourceFeed = if (Test-Path variable:runtimeSourceFeed) { $runtimeSourceFeed } else { $null } # Base-64 encoded SAS token that has permission to storage container described by $runtimeSourceFeed [string]$runtimeSourceFeedKey = if (Test-Path variable:runtimeSourceFeedKey) { $runtimeSourceFeedKey } else { $null } function Create-Directory ([string[]] $path) { New-Item -Path $path -Force -ItemType 'Directory' | Out-Null } function Unzip([string]$zipfile, [string]$outpath) { Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath) } # This will exec a process using the console and return it's exit code. # This will not throw when the process fails. # Returns process exit code. function Exec-Process([string]$command, [string]$commandArgs) { $startInfo = New-Object System.Diagnostics.ProcessStartInfo $startInfo.FileName = $command $startInfo.Arguments = $commandArgs $startInfo.UseShellExecute = $false $startInfo.WorkingDirectory = Get-Location $process = New-Object System.Diagnostics.Process $process.StartInfo = $startInfo $process.Start() | Out-Null $finished = $false try { while (-not $process.WaitForExit(100)) { # Non-blocking loop done to allow ctr-c interrupts } $finished = $true return $global:LASTEXITCODE = $process.ExitCode } finally { # If we didn't finish then an error occurred or the user hit ctrl-c. Either # way kill the process if (-not $finished) { $process.Kill() } } } # Take the given block, print it, print what the block probably references from the current set of # variables using low-effort string matching, then run the block. # # This is intended to replace the pattern of manually copy-pasting a command, wrapping it in quotes, # and printing it using "Write-Host". The copy-paste method is more readable in build logs, but less # maintainable and less reliable. It is easy to make a mistake and modify the command without # properly updating the "Write-Host" line, resulting in misleading build logs. The probability of # this mistake makes the pattern hard to trust when it shows up in build logs. Finding the bug in # existing source code can also be difficult, because the strings are not aligned to each other and # the line may be 300+ columns long. # # By removing the need to maintain two copies of the command, Exec-BlockVerbosely avoids the issues. # # In Bash (or any posix-like shell), "set -x" prints usable verbose output automatically. # "Set-PSDebug" appears to be similar at first glance, but unfortunately, it isn't very useful: it # doesn't print any info about the variables being used by the command, which is normally the # interesting part to diagnose. function Exec-BlockVerbosely([scriptblock] $block) { Write-Host "--- Running script block:" $blockString = $block.ToString().Trim() Write-Host $blockString Write-Host "--- List of variables that might be used:" # For each variable x in the environment, check the block for a reference to x via simple "$x" or # "@x" syntax. This doesn't detect other ways to reference variables ("${x}" nor "$variable:x", # among others). It only catches what this function was originally written for: simple # command-line commands. $variableTable = Get-Variable | Where-Object { $blockString.Contains("`$$($_.Name)") -or $blockString.Contains("@$($_.Name)") } | Format-Table -AutoSize -HideTableHeaders -Wrap | Out-String Write-Host $variableTable.Trim() Write-Host "--- Executing:" & $block Write-Host "--- Done running script block!" } # createSdkLocationFile parameter enables a file being generated under the toolset directory # which writes the sdk's location into. This is only necessary for cmd --> powershell invocations # as dot sourcing isn't possible. function InitializeDotNetCli([bool]$install, [bool]$createSdkLocationFile) { if (Test-Path variable:global:_DotNetInstallDir) { return $global:_DotNetInstallDir } # Don't resolve runtime, shared framework, or SDK from other locations to ensure build determinism $env:DOTNET_MULTILEVEL_LOOKUP=0 # Disable first run since we do not need all ASP.NET packages restored. $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 # Disable telemetry on CI. if ($ci) { $env:DOTNET_CLI_TELEMETRY_OPTOUT=1 } # Source Build uses DotNetCoreSdkDir variable if ($env:DotNetCoreSdkDir -ne $null) { $env:DOTNET_INSTALL_DIR = $env:DotNetCoreSdkDir } # Find the first path on %PATH% that contains the dotnet.exe if ($useInstalledDotNetCli -and (-not $globalJsonHasRuntimes) -and ($env:DOTNET_INSTALL_DIR -eq $null)) { $dotnetExecutable = GetExecutableFileName 'dotnet' $dotnetCmd = Get-Command $dotnetExecutable -ErrorAction SilentlyContinue if ($dotnetCmd -ne $null) { $env:DOTNET_INSTALL_DIR = Split-Path $dotnetCmd.Path -Parent } } $dotnetSdkVersion = $GlobalJson.tools.dotnet # Use dotnet installation specified in DOTNET_INSTALL_DIR if it contains the required SDK version, # otherwise install the dotnet CLI and SDK to repo local .dotnet directory to avoid potential permission issues. if ((-not $globalJsonHasRuntimes) -and (-not [string]::IsNullOrEmpty($env:DOTNET_INSTALL_DIR)) -and (Test-Path(Join-Path $env:DOTNET_INSTALL_DIR "sdk\$dotnetSdkVersion"))) { $dotnetRoot = $env:DOTNET_INSTALL_DIR } else { $dotnetRoot = Join-Path $RepoRoot '.dotnet' if (-not (Test-Path(Join-Path $dotnetRoot "sdk\$dotnetSdkVersion"))) { if ($install) { InstallDotNetSdk $dotnetRoot $dotnetSdkVersion } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unable to find dotnet with SDK version '$dotnetSdkVersion'" ExitWithExitCode 1 } } $env:DOTNET_INSTALL_DIR = $dotnetRoot } # Creates a temporary file under the toolset dir. # The following code block is protecting against concurrent access so that this function can # be called in parallel. if ($createSdkLocationFile) { do { $sdkCacheFileTemp = Join-Path $ToolsetDir $([System.IO.Path]::GetRandomFileName()) } until (!(Test-Path $sdkCacheFileTemp)) Set-Content -Path $sdkCacheFileTemp -Value $dotnetRoot try { Move-Item -Force $sdkCacheFileTemp (Join-Path $ToolsetDir 'sdk.txt') } catch { # Somebody beat us Remove-Item -Path $sdkCacheFileTemp } } # Add dotnet to PATH. This prevents any bare invocation of dotnet in custom # build steps from using anything other than what we've downloaded. # It also ensures that VS msbuild will use the downloaded sdk targets. $env:PATH = "$dotnetRoot;$env:PATH" # Make Sure that our bootstrapped dotnet cli is available in future steps of the Azure Pipelines build Write-PipelinePrependPath -Path $dotnetRoot Write-PipelineSetVariable -Name 'DOTNET_MULTILEVEL_LOOKUP' -Value '0' Write-PipelineSetVariable -Name 'DOTNET_SKIP_FIRST_TIME_EXPERIENCE' -Value '1' return $global:_DotNetInstallDir = $dotnetRoot } function Retry($downloadBlock, $maxRetries = 5) { $retries = 1 while($true) { try { & $downloadBlock break } catch { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_ } if (++$retries -le $maxRetries) { $delayInSeconds = [math]::Pow(2, $retries) - 1 # Exponential backoff Write-Host "Retrying. Waiting for $delayInSeconds seconds before next attempt ($retries of $maxRetries)." Start-Sleep -Seconds $delayInSeconds } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unable to download file in $maxRetries attempts." break } } } function GetDotNetInstallScript([string] $dotnetRoot) { $installScript = Join-Path $dotnetRoot 'dotnet-install.ps1' if (!(Test-Path $installScript)) { Create-Directory $dotnetRoot $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit $uri = "https://dotnet.microsoft.com/download/dotnet/scripts/$dotnetInstallScriptVersion/dotnet-install.ps1" Retry({ Write-Host "GET $uri" Invoke-WebRequest $uri -OutFile $installScript }) } return $installScript } function InstallDotNetSdk([string] $dotnetRoot, [string] $version, [string] $architecture = '', [switch] $noPath) { InstallDotNet $dotnetRoot $version $architecture '' $false $runtimeSourceFeed $runtimeSourceFeedKey -noPath:$noPath } function InstallDotNet([string] $dotnetRoot, [string] $version, [string] $architecture = '', [string] $runtime = '', [bool] $skipNonVersionedFiles = $false, [string] $runtimeSourceFeed = '', [string] $runtimeSourceFeedKey = '', [switch] $noPath) { $installScript = GetDotNetInstallScript $dotnetRoot $installParameters = @{ Version = $version InstallDir = $dotnetRoot } if ($architecture) { $installParameters.Architecture = $architecture } if ($runtime) { $installParameters.Runtime = $runtime } if ($skipNonVersionedFiles) { $installParameters.SkipNonVersionedFiles = $skipNonVersionedFiles } if ($noPath) { $installParameters.NoPath = $True } try { & $installScript @installParameters } catch { if ($runtimeSourceFeed -or $runtimeSourceFeedKey) { Write-Host "Failed to install dotnet from public location. Trying from '$runtimeSourceFeed'" if ($runtimeSourceFeed) { $installParameters.AzureFeed = $runtimeSourceFeed } if ($runtimeSourceFeedKey) { $decodedBytes = [System.Convert]::FromBase64String($runtimeSourceFeedKey) $decodedString = [System.Text.Encoding]::UTF8.GetString($decodedBytes) $installParameters.FeedCredential = $decodedString } try { & $installScript @installParameters } catch { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Failed to install dotnet from custom location '$runtimeSourceFeed'." ExitWithExitCode 1 } } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Failed to install dotnet from public location." ExitWithExitCode 1 } } } # # Locates Visual Studio MSBuild installation. # The preference order for MSBuild to use is as follows: # # 1. MSBuild from an active VS command prompt # 2. MSBuild from a compatible VS installation # 3. MSBuild from the xcopy tool package # # Returns full path to msbuild.exe. # Throws on failure. # function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = $null) { if (-not (IsWindowsPlatform)) { throw "Cannot initialize Visual Studio on non-Windows" } if (Test-Path variable:global:_MSBuildExe) { return $global:_MSBuildExe } # Minimum VS version to require. $vsMinVersionReqdStr = '16.8' $vsMinVersionReqd = [Version]::new($vsMinVersionReqdStr) # If the version of msbuild is going to be xcopied, # use this version. Version matches a package here: # https://dev.azure.com/dnceng/public/_packaging?_a=package&feed=dotnet-eng&package=RoslynTools.MSBuild&protocolType=NuGet&version=16.10.0-preview2&view=overview $defaultXCopyMSBuildVersion = '16.10.0-preview2' if (!$vsRequirements) { $vsRequirements = $GlobalJson.tools.vs } $vsMinVersionStr = if ($vsRequirements.version) { $vsRequirements.version } else { $vsMinVersionReqdStr } $vsMinVersion = [Version]::new($vsMinVersionStr) # Try msbuild command available in the environment. if ($env:VSINSTALLDIR -ne $null) { $msbuildCmd = Get-Command 'msbuild.exe' -ErrorAction SilentlyContinue if ($msbuildCmd -ne $null) { # Workaround for https://github.com/dotnet/roslyn/issues/35793 # Due to this issue $msbuildCmd.Version returns 0.0.0.0 for msbuild.exe 16.2+ $msbuildVersion = [Version]::new((Get-Item $msbuildCmd.Path).VersionInfo.ProductVersion.Split([char[]]@('-', '+'))[0]) if ($msbuildVersion -ge $vsMinVersion) { return $global:_MSBuildExe = $msbuildCmd.Path } # Report error - the developer environment is initialized with incompatible VS version. throw "Developer Command Prompt for VS $($env:VisualStudioVersion) is not recent enough. Please upgrade to $vsMinVersionStr or build from a plain CMD window" } } # Locate Visual Studio installation or download x-copy msbuild. $vsInfo = LocateVisualStudio $vsRequirements if ($vsInfo -ne $null) { $vsInstallDir = $vsInfo.installationPath $vsMajorVersion = $vsInfo.installationVersion.Split('.')[0] InitializeVisualStudioEnvironmentVariables $vsInstallDir $vsMajorVersion } else { if (Get-Member -InputObject $GlobalJson.tools -Name 'xcopy-msbuild') { $xcopyMSBuildVersion = $GlobalJson.tools.'xcopy-msbuild' $vsMajorVersion = $xcopyMSBuildVersion.Split('.')[0] } else { #if vs version provided in global.json is incompatible (too low) then use the default version for xcopy msbuild download if($vsMinVersion -lt $vsMinVersionReqd){ Write-Host "Using xcopy-msbuild version of $defaultXCopyMSBuildVersion since VS version $vsMinVersionStr provided in global.json is not compatible" $xcopyMSBuildVersion = $defaultXCopyMSBuildVersion } else{ # If the VS version IS compatible, look for an xcopy msbuild package # with a version matching VS. # Note: If this version does not exist, then an explicit version of xcopy msbuild # can be specified in global.json. This will be required for pre-release versions of msbuild. $vsMajorVersion = $vsMinVersion.Major $vsMinorVersion = $vsMinVersion.Minor $xcopyMSBuildVersion = "$vsMajorVersion.$vsMinorVersion.0" } } $vsInstallDir = $null if ($xcopyMSBuildVersion.Trim() -ine "none") { $vsInstallDir = InitializeXCopyMSBuild $xcopyMSBuildVersion $install if ($vsInstallDir -eq $null) { throw "Could not xcopy msbuild. Please check that package 'RoslynTools.MSBuild @ $xcopyMSBuildVersion' exists on feed 'dotnet-eng'." } } if ($vsInstallDir -eq $null) { throw 'Unable to find Visual Studio that has required version and components installed' } } $msbuildVersionDir = if ([int]$vsMajorVersion -lt 16) { "$vsMajorVersion.0" } else { "Current" } $local:BinFolder = Join-Path $vsInstallDir "MSBuild\$msbuildVersionDir\Bin" $local:Prefer64bit = if (Get-Member -InputObject $vsRequirements -Name 'Prefer64bit') { $vsRequirements.Prefer64bit } else { $false } if ($local:Prefer64bit -and (Test-Path(Join-Path $local:BinFolder "amd64"))) { $global:_MSBuildExe = Join-Path $local:BinFolder "amd64\msbuild.exe" } else { $global:_MSBuildExe = Join-Path $local:BinFolder "msbuild.exe" } return $global:_MSBuildExe } function InitializeVisualStudioEnvironmentVariables([string] $vsInstallDir, [string] $vsMajorVersion) { $env:VSINSTALLDIR = $vsInstallDir Set-Item "env:VS$($vsMajorVersion)0COMNTOOLS" (Join-Path $vsInstallDir "Common7\Tools\") $vsSdkInstallDir = Join-Path $vsInstallDir "VSSDK\" if (Test-Path $vsSdkInstallDir) { Set-Item "env:VSSDK$($vsMajorVersion)0Install" $vsSdkInstallDir $env:VSSDKInstall = $vsSdkInstallDir } } function InstallXCopyMSBuild([string]$packageVersion) { return InitializeXCopyMSBuild $packageVersion -install $true } function InitializeXCopyMSBuild([string]$packageVersion, [bool]$install) { $packageName = 'RoslynTools.MSBuild' $packageDir = Join-Path $ToolsDir "msbuild\$packageVersion" $packagePath = Join-Path $packageDir "$packageName.$packageVersion.nupkg" if (!(Test-Path $packageDir)) { if (!$install) { return $null } Create-Directory $packageDir Write-Host "Downloading $packageName $packageVersion" $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit Retry({ Invoke-WebRequest "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/flat2/$packageName/$packageVersion/$packageName.$packageVersion.nupkg" -OutFile $packagePath }) Unzip $packagePath $packageDir } return Join-Path $packageDir 'tools' } # # Locates Visual Studio instance that meets the minimal requirements specified by tools.vs object in global.json. # # The following properties of tools.vs are recognized: # "version": "{major}.{minor}" # Two part minimal VS version, e.g. "15.9", "16.0", etc. # "components": ["componentId1", "componentId2", ...] # Array of ids of workload components that must be available in the VS instance. # See e.g. https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-enterprise?view=vs-2017 # # Returns JSON describing the located VS instance (same format as returned by vswhere), # or $null if no instance meeting the requirements is found on the machine. # function LocateVisualStudio([object]$vsRequirements = $null){ if (-not (IsWindowsPlatform)) { throw "Cannot run vswhere on non-Windows platforms." } if (Get-Member -InputObject $GlobalJson.tools -Name 'vswhere') { $vswhereVersion = $GlobalJson.tools.vswhere } else { $vswhereVersion = '2.5.2' } $vsWhereDir = Join-Path $ToolsDir "vswhere\$vswhereVersion" $vsWhereExe = Join-Path $vsWhereDir 'vswhere.exe' if (!(Test-Path $vsWhereExe)) { Create-Directory $vsWhereDir Write-Host 'Downloading vswhere' Retry({ Invoke-WebRequest "https://netcorenativeassets.blob.core.windows.net/resource-packages/external/windows/vswhere/$vswhereVersion/vswhere.exe" -OutFile $vswhereExe }) } if (!$vsRequirements) { $vsRequirements = $GlobalJson.tools.vs } $args = @('-latest', '-format', 'json', '-requires', 'Microsoft.Component.MSBuild', '-products', '*') if (!$excludePrereleaseVS) { $args += '-prerelease' } if (Get-Member -InputObject $vsRequirements -Name 'version') { $args += '-version' $args += $vsRequirements.version } if (Get-Member -InputObject $vsRequirements -Name 'components') { foreach ($component in $vsRequirements.components) { $args += '-requires' $args += $component } } $vsInfo =& $vsWhereExe $args | ConvertFrom-Json if ($lastExitCode -ne 0) { return $null } # use first matching instance return $vsInfo[0] } function InitializeBuildTool() { if (Test-Path variable:global:_BuildTool) { # If the requested msbuild parameters do not match, clear the cached variables. if($global:_BuildTool.Contains('ExcludePrereleaseVS') -and $global:_BuildTool.ExcludePrereleaseVS -ne $excludePrereleaseVS) { Remove-Item variable:global:_BuildTool Remove-Item variable:global:_MSBuildExe } else { return $global:_BuildTool } } if (-not $msbuildEngine) { $msbuildEngine = GetDefaultMSBuildEngine } # Initialize dotnet cli if listed in 'tools' $dotnetRoot = $null if (Get-Member -InputObject $GlobalJson.tools -Name 'dotnet') { $dotnetRoot = InitializeDotNetCli -install:$restore } if ($msbuildEngine -eq 'dotnet') { if (!$dotnetRoot) { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "/global.json must specify 'tools.dotnet'." ExitWithExitCode 1 } $dotnetPath = Join-Path $dotnetRoot (GetExecutableFileName 'dotnet') $buildTool = @{ Path = $dotnetPath; Command = 'msbuild'; Tool = 'dotnet'; Framework = 'netcoreapp3.1' } } elseif ($msbuildEngine -eq "vs") { try { $msbuildPath = InitializeVisualStudioMSBuild -install:$restore } catch { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_ ExitWithExitCode 1 } $buildTool = @{ Path = $msbuildPath; Command = ""; Tool = "vs"; Framework = "net472"; ExcludePrereleaseVS = $excludePrereleaseVS } } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unexpected value of -msbuildEngine: '$msbuildEngine'." ExitWithExitCode 1 } return $global:_BuildTool = $buildTool } function GetDefaultMSBuildEngine() { # Presence of tools.vs indicates the repo needs to build using VS msbuild on Windows. if (Get-Member -InputObject $GlobalJson.tools -Name 'vs') { return 'vs' } if (Get-Member -InputObject $GlobalJson.tools -Name 'dotnet') { return 'dotnet' } Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "-msbuildEngine must be specified, or /global.json must specify 'tools.dotnet' or 'tools.vs'." ExitWithExitCode 1 } function GetNuGetPackageCachePath() { if ($env:NUGET_PACKAGES -eq $null) { # Use local cache on CI to ensure deterministic build. # Avoid using the http cache as workaround for https://github.com/NuGet/Home/issues/3116 # use global cache in dev builds to avoid cost of downloading packages. # For directory normalization, see also: https://github.com/NuGet/Home/issues/7968 if ($useGlobalNuGetCache) { $env:NUGET_PACKAGES = Join-Path $env:UserProfile '.nuget\packages\' } else { $env:NUGET_PACKAGES = Join-Path $RepoRoot '.packages\' $env:RESTORENOCACHE = $true } } return $env:NUGET_PACKAGES } # Returns a full path to an Arcade SDK task project file. function GetSdkTaskProject([string]$taskName) { return Join-Path (Split-Path (InitializeToolset) -Parent) "SdkTasks\$taskName.proj" } function InitializeNativeTools() { if (-Not (Test-Path variable:DisableNativeToolsetInstalls) -And (Get-Member -InputObject $GlobalJson -Name "native-tools")) { $nativeArgs= @{} if ($ci) { $nativeArgs = @{ InstallDirectory = "$ToolsDir" } } & "$PSScriptRoot/init-tools-native.ps1" @nativeArgs } } function InitializeToolset() { if (Test-Path variable:global:_ToolsetBuildProj) { return $global:_ToolsetBuildProj } $nugetCache = GetNuGetPackageCachePath $toolsetVersion = $GlobalJson.'msbuild-sdks'.'Microsoft.DotNet.Arcade.Sdk' $toolsetLocationFile = Join-Path $ToolsetDir "$toolsetVersion.txt" if (Test-Path $toolsetLocationFile) { $path = Get-Content $toolsetLocationFile -TotalCount 1 if (Test-Path $path) { return $global:_ToolsetBuildProj = $path } } if (-not $restore) { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Toolset version $toolsetVersion has not been restored." ExitWithExitCode 1 } $buildTool = InitializeBuildTool $proj = Join-Path $ToolsetDir 'restore.proj' $bl = if ($binaryLog) { '/bl:' + (Join-Path $LogDir 'ToolsetRestore.binlog') } else { '' } '<Project Sdk="Microsoft.DotNet.Arcade.Sdk"/>' | Set-Content $proj MSBuild-Core $proj $bl /t:__WriteToolsetLocation /clp:ErrorsOnly`;NoSummary /p:__ToolsetLocationOutputFile=$toolsetLocationFile $path = Get-Content $toolsetLocationFile -Encoding UTF8 -TotalCount 1 if (!(Test-Path $path)) { throw "Invalid toolset path: $path" } return $global:_ToolsetBuildProj = $path } function ExitWithExitCode([int] $exitCode) { if ($ci -and $prepareMachine) { Stop-Processes } exit $exitCode } # Check if $LASTEXITCODE is a nonzero exit code (NZEC). If so, print a Azure Pipeline error for # diagnostics, then exit the script with the $LASTEXITCODE. function Exit-IfNZEC([string] $category = "General") { Write-Host "Exit code $LASTEXITCODE" if ($LASTEXITCODE -ne 0) { $message = "Last command failed with exit code $LASTEXITCODE." Write-PipelineTelemetryError -Force -Category $category -Message $message ExitWithExitCode $LASTEXITCODE } } function Stop-Processes() { Write-Host 'Killing running build processes...' foreach ($processName in $processesToStopOnExit) { Get-Process -Name $processName -ErrorAction SilentlyContinue | Stop-Process } } # # Executes msbuild (or 'dotnet msbuild') with arguments passed to the function. # The arguments are automatically quoted. # Terminates the script if the build fails. # function MSBuild() { if ($pipelinesLog) { $buildTool = InitializeBuildTool if ($ci -and $buildTool.Tool -eq 'dotnet') { $env:NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS = 20 $env:NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS = 20 Write-PipelineSetVariable -Name 'NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS' -Value '20' Write-PipelineSetVariable -Name 'NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS' -Value '20' } $toolsetBuildProject = InitializeToolset $basePath = Split-Path -parent $toolsetBuildProject $possiblePaths = @( # new scripts need to work with old packages, so we need to look for the old names/versions (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.Arcade.Sdk.dll')), (Join-Path $basePath (Join-Path netcoreapp2.1 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path netcoreapp2.1 'Microsoft.DotNet.Arcade.Sdk.dll')) ) $selectedPath = $null foreach ($path in $possiblePaths) { if (Test-Path $path -PathType Leaf) { $selectedPath = $path break } } if (-not $selectedPath) { Write-PipelineTelemetryError -Category 'Build' -Message 'Unable to find arcade sdk logger assembly.' ExitWithExitCode 1 } $args += "/logger:$selectedPath" } MSBuild-Core @args } # # Executes msbuild (or 'dotnet msbuild') with arguments passed to the function. # The arguments are automatically quoted. # Terminates the script if the build fails. # function MSBuild-Core() { if ($ci) { if (!$binaryLog -and !$excludeCIBinarylog) { Write-PipelineTelemetryError -Category 'Build' -Message 'Binary log must be enabled in CI build, or explicitly opted-out from with the -excludeCIBinarylog switch.' ExitWithExitCode 1 } if ($nodeReuse) { Write-PipelineTelemetryError -Category 'Build' -Message 'Node reuse must be disabled in CI build.' ExitWithExitCode 1 } } $buildTool = InitializeBuildTool $cmdArgs = "$($buildTool.Command) /m /nologo /clp:Summary /v:$verbosity /nr:$nodeReuse /p:ContinuousIntegrationBuild=$ci" if ($warnAsError) { $cmdArgs += ' /warnaserror /p:TreatWarningsAsErrors=true' } else { $cmdArgs += ' /p:TreatWarningsAsErrors=false' } foreach ($arg in $args) { if ($null -ne $arg -and $arg.Trim() -ne "") { if ($arg.EndsWith('\')) { $arg = $arg + "\" } $cmdArgs += " `"$arg`"" } } $env:ARCADE_BUILD_TOOL_COMMAND = "$($buildTool.Path) $cmdArgs" $exitCode = Exec-Process $buildTool.Path $cmdArgs if ($exitCode -ne 0) { # We should not Write-PipelineTaskError here because that message shows up in the build summary # The build already logged an error, that's the reason it failed. Producing an error here only adds noise. Write-Host "Build failed with exit code $exitCode. Check errors above." -ForegroundColor Red $buildLog = GetMSBuildBinaryLogCommandLineArgument $args if ($null -ne $buildLog) { Write-Host "See log: $buildLog" -ForegroundColor DarkGray } if ($ci) { Write-PipelineSetResult -Result "Failed" -Message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error ExitWithExitCode 0 } else { ExitWithExitCode $exitCode } } } function GetMSBuildBinaryLogCommandLineArgument($arguments) { foreach ($argument in $arguments) { if ($argument -ne $null) { $arg = $argument.Trim() if ($arg.StartsWith('/bl:', "OrdinalIgnoreCase")) { return $arg.Substring('/bl:'.Length) } if ($arg.StartsWith('/binaryLogger:', 'OrdinalIgnoreCase')) { return $arg.Substring('/binaryLogger:'.Length) } } } return $null } function GetExecutableFileName($baseName) { if (IsWindowsPlatform) { return "$baseName.exe" } else { return $baseName } } function IsWindowsPlatform() { return [environment]::OSVersion.Platform -eq [PlatformID]::Win32NT } function Get-Darc($version) { $darcPath = "$TempDir\darc\$(New-Guid)" if ($version -ne $null) { & $PSScriptRoot\darc-init.ps1 -toolpath $darcPath -darcVersion $version | Out-Host } else { & $PSScriptRoot\darc-init.ps1 -toolpath $darcPath | Out-Host } return "$darcPath\darc.exe" } . $PSScriptRoot\pipeline-logging-functions.ps1 $RepoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\..\') $EngRoot = Resolve-Path (Join-Path $PSScriptRoot '..') $ArtifactsDir = Join-Path $RepoRoot 'artifacts' $ToolsetDir = Join-Path $ArtifactsDir 'toolset' $ToolsDir = Join-Path $RepoRoot '.tools' $LogDir = Join-Path (Join-Path $ArtifactsDir 'log') $configuration $TempDir = Join-Path (Join-Path $ArtifactsDir 'tmp') $configuration $GlobalJson = Get-Content -Raw -Path (Join-Path $RepoRoot 'global.json') | ConvertFrom-Json # true if global.json contains a "runtimes" section $globalJsonHasRuntimes = if ($GlobalJson.tools.PSObject.Properties.Name -Match 'runtimes') { $true } else { $false } Create-Directory $ToolsetDir Create-Directory $TempDir Create-Directory $LogDir Write-PipelineSetVariable -Name 'Artifacts' -Value $ArtifactsDir Write-PipelineSetVariable -Name 'Artifacts.Toolset' -Value $ToolsetDir Write-PipelineSetVariable -Name 'Artifacts.Log' -Value $LogDir Write-PipelineSetVariable -Name 'TEMP' -Value $TempDir Write-PipelineSetVariable -Name 'TMP' -Value $TempDir # Import custom tools configuration, if present in the repo. # Note: Import in global scope so that the script set top-level variables without qualification. if (!$disableConfigureToolsetImport) { $configureToolsetScript = Join-Path $EngRoot 'configure-toolset.ps1' if (Test-Path $configureToolsetScript) { . $configureToolsetScript if ((Test-Path variable:failOnConfigureToolsetError) -And $failOnConfigureToolsetError) { if ((Test-Path variable:LastExitCode) -And ($LastExitCode -ne 0)) { Write-PipelineTelemetryError -Category 'Build' -Message 'configure-toolset.ps1 returned a non-zero exit code' ExitWithExitCode $LastExitCode } } } }
# Initialize variables if they aren't already defined. # These may be defined as parameters of the importing script, or set after importing this script. # CI mode - set to true on CI server for PR validation build or official build. [bool]$ci = if (Test-Path variable:ci) { $ci } else { $false } # Build configuration. Common values include 'Debug' and 'Release', but the repository may use other names. [string]$configuration = if (Test-Path variable:configuration) { $configuration } else { 'Debug' } # Set to true to opt out of outputting binary log while running in CI [bool]$excludeCIBinarylog = if (Test-Path variable:excludeCIBinarylog) { $excludeCIBinarylog } else { $false } # Set to true to output binary log from msbuild. Note that emitting binary log slows down the build. [bool]$binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $ci -and !$excludeCIBinarylog } # Set to true to use the pipelines logger which will enable Azure logging output. # https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md # This flag is meant as a temporary opt-opt for the feature while validate it across # our consumers. It will be deleted in the future. [bool]$pipelinesLog = if (Test-Path variable:pipelinesLog) { $pipelinesLog } else { $ci } # Turns on machine preparation/clean up code that changes the machine state (e.g. kills build processes). [bool]$prepareMachine = if (Test-Path variable:prepareMachine) { $prepareMachine } else { $false } # True to restore toolsets and dependencies. [bool]$restore = if (Test-Path variable:restore) { $restore } else { $true } # Adjusts msbuild verbosity level. [string]$verbosity = if (Test-Path variable:verbosity) { $verbosity } else { 'minimal' } # Set to true to reuse msbuild nodes. Recommended to not reuse on CI. [bool]$nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { !$ci } # Configures warning treatment in msbuild. [bool]$warnAsError = if (Test-Path variable:warnAsError) { $warnAsError } else { $true } # Specifies which msbuild engine to use for build: 'vs', 'dotnet' or unspecified (determined based on presence of tools.vs in global.json). [string]$msbuildEngine = if (Test-Path variable:msbuildEngine) { $msbuildEngine } else { $null } # True to attempt using .NET Core already that meets requirements specified in global.json # installed on the machine instead of downloading one. [bool]$useInstalledDotNetCli = if (Test-Path variable:useInstalledDotNetCli) { $useInstalledDotNetCli } else { $true } # Enable repos to use a particular version of the on-line dotnet-install scripts. # default URL: https://dotnet.microsoft.com/download/dotnet/scripts/v1/dotnet-install.ps1 [string]$dotnetInstallScriptVersion = if (Test-Path variable:dotnetInstallScriptVersion) { $dotnetInstallScriptVersion } else { 'v1' } # True to use global NuGet cache instead of restoring packages to repository-local directory. [bool]$useGlobalNuGetCache = if (Test-Path variable:useGlobalNuGetCache) { $useGlobalNuGetCache } else { !$ci } # True to exclude prerelease versions Visual Studio during build [bool]$excludePrereleaseVS = if (Test-Path variable:excludePrereleaseVS) { $excludePrereleaseVS } else { $false } # An array of names of processes to stop on script exit if prepareMachine is true. $processesToStopOnExit = if (Test-Path variable:processesToStopOnExit) { $processesToStopOnExit } else { @('msbuild', 'dotnet', 'vbcscompiler') } $disableConfigureToolsetImport = if (Test-Path variable:disableConfigureToolsetImport) { $disableConfigureToolsetImport } else { $null } set-strictmode -version 2.0 $ErrorActionPreference = 'Stop' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # If specifies, provides an alternate path for getting .NET Core SDKs and Runtimes. This script will still try public sources first. [string]$runtimeSourceFeed = if (Test-Path variable:runtimeSourceFeed) { $runtimeSourceFeed } else { $null } # Base-64 encoded SAS token that has permission to storage container described by $runtimeSourceFeed [string]$runtimeSourceFeedKey = if (Test-Path variable:runtimeSourceFeedKey) { $runtimeSourceFeedKey } else { $null } function Create-Directory ([string[]] $path) { New-Item -Path $path -Force -ItemType 'Directory' | Out-Null } function Unzip([string]$zipfile, [string]$outpath) { Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath) } # This will exec a process using the console and return it's exit code. # This will not throw when the process fails. # Returns process exit code. function Exec-Process([string]$command, [string]$commandArgs) { $startInfo = New-Object System.Diagnostics.ProcessStartInfo $startInfo.FileName = $command $startInfo.Arguments = $commandArgs $startInfo.UseShellExecute = $false $startInfo.WorkingDirectory = Get-Location $process = New-Object System.Diagnostics.Process $process.StartInfo = $startInfo $process.Start() | Out-Null $finished = $false try { while (-not $process.WaitForExit(100)) { # Non-blocking loop done to allow ctr-c interrupts } $finished = $true return $global:LASTEXITCODE = $process.ExitCode } finally { # If we didn't finish then an error occurred or the user hit ctrl-c. Either # way kill the process if (-not $finished) { $process.Kill() } } } # Take the given block, print it, print what the block probably references from the current set of # variables using low-effort string matching, then run the block. # # This is intended to replace the pattern of manually copy-pasting a command, wrapping it in quotes, # and printing it using "Write-Host". The copy-paste method is more readable in build logs, but less # maintainable and less reliable. It is easy to make a mistake and modify the command without # properly updating the "Write-Host" line, resulting in misleading build logs. The probability of # this mistake makes the pattern hard to trust when it shows up in build logs. Finding the bug in # existing source code can also be difficult, because the strings are not aligned to each other and # the line may be 300+ columns long. # # By removing the need to maintain two copies of the command, Exec-BlockVerbosely avoids the issues. # # In Bash (or any posix-like shell), "set -x" prints usable verbose output automatically. # "Set-PSDebug" appears to be similar at first glance, but unfortunately, it isn't very useful: it # doesn't print any info about the variables being used by the command, which is normally the # interesting part to diagnose. function Exec-BlockVerbosely([scriptblock] $block) { Write-Host "--- Running script block:" $blockString = $block.ToString().Trim() Write-Host $blockString Write-Host "--- List of variables that might be used:" # For each variable x in the environment, check the block for a reference to x via simple "$x" or # "@x" syntax. This doesn't detect other ways to reference variables ("${x}" nor "$variable:x", # among others). It only catches what this function was originally written for: simple # command-line commands. $variableTable = Get-Variable | Where-Object { $blockString.Contains("`$$($_.Name)") -or $blockString.Contains("@$($_.Name)") } | Format-Table -AutoSize -HideTableHeaders -Wrap | Out-String Write-Host $variableTable.Trim() Write-Host "--- Executing:" & $block Write-Host "--- Done running script block!" } # createSdkLocationFile parameter enables a file being generated under the toolset directory # which writes the sdk's location into. This is only necessary for cmd --> powershell invocations # as dot sourcing isn't possible. function InitializeDotNetCli([bool]$install, [bool]$createSdkLocationFile) { if (Test-Path variable:global:_DotNetInstallDir) { return $global:_DotNetInstallDir } # Don't resolve runtime, shared framework, or SDK from other locations to ensure build determinism $env:DOTNET_MULTILEVEL_LOOKUP=0 # Disable first run since we do not need all ASP.NET packages restored. $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 # Disable telemetry on CI. if ($ci) { $env:DOTNET_CLI_TELEMETRY_OPTOUT=1 # In case of network error, try to log the current IP for reference Try-LogClientIpAddress } # Source Build uses DotNetCoreSdkDir variable if ($env:DotNetCoreSdkDir -ne $null) { $env:DOTNET_INSTALL_DIR = $env:DotNetCoreSdkDir } # Find the first path on %PATH% that contains the dotnet.exe if ($useInstalledDotNetCli -and (-not $globalJsonHasRuntimes) -and ($env:DOTNET_INSTALL_DIR -eq $null)) { $dotnetExecutable = GetExecutableFileName 'dotnet' $dotnetCmd = Get-Command $dotnetExecutable -ErrorAction SilentlyContinue if ($dotnetCmd -ne $null) { $env:DOTNET_INSTALL_DIR = Split-Path $dotnetCmd.Path -Parent } } $dotnetSdkVersion = $GlobalJson.tools.dotnet # Use dotnet installation specified in DOTNET_INSTALL_DIR if it contains the required SDK version, # otherwise install the dotnet CLI and SDK to repo local .dotnet directory to avoid potential permission issues. if ((-not $globalJsonHasRuntimes) -and (-not [string]::IsNullOrEmpty($env:DOTNET_INSTALL_DIR)) -and (Test-Path(Join-Path $env:DOTNET_INSTALL_DIR "sdk\$dotnetSdkVersion"))) { $dotnetRoot = $env:DOTNET_INSTALL_DIR } else { $dotnetRoot = Join-Path $RepoRoot '.dotnet' if (-not (Test-Path(Join-Path $dotnetRoot "sdk\$dotnetSdkVersion"))) { if ($install) { InstallDotNetSdk $dotnetRoot $dotnetSdkVersion } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unable to find dotnet with SDK version '$dotnetSdkVersion'" ExitWithExitCode 1 } } $env:DOTNET_INSTALL_DIR = $dotnetRoot } # Creates a temporary file under the toolset dir. # The following code block is protecting against concurrent access so that this function can # be called in parallel. if ($createSdkLocationFile) { do { $sdkCacheFileTemp = Join-Path $ToolsetDir $([System.IO.Path]::GetRandomFileName()) } until (!(Test-Path $sdkCacheFileTemp)) Set-Content -Path $sdkCacheFileTemp -Value $dotnetRoot try { Move-Item -Force $sdkCacheFileTemp (Join-Path $ToolsetDir 'sdk.txt') } catch { # Somebody beat us Remove-Item -Path $sdkCacheFileTemp } } # Add dotnet to PATH. This prevents any bare invocation of dotnet in custom # build steps from using anything other than what we've downloaded. # It also ensures that VS msbuild will use the downloaded sdk targets. $env:PATH = "$dotnetRoot;$env:PATH" # Make Sure that our bootstrapped dotnet cli is available in future steps of the Azure Pipelines build Write-PipelinePrependPath -Path $dotnetRoot Write-PipelineSetVariable -Name 'DOTNET_MULTILEVEL_LOOKUP' -Value '0' Write-PipelineSetVariable -Name 'DOTNET_SKIP_FIRST_TIME_EXPERIENCE' -Value '1' return $global:_DotNetInstallDir = $dotnetRoot } function Retry($downloadBlock, $maxRetries = 5) { $retries = 1 while($true) { try { & $downloadBlock break } catch { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_ } if (++$retries -le $maxRetries) { $delayInSeconds = [math]::Pow(2, $retries) - 1 # Exponential backoff Write-Host "Retrying. Waiting for $delayInSeconds seconds before next attempt ($retries of $maxRetries)." Start-Sleep -Seconds $delayInSeconds } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unable to download file in $maxRetries attempts." break } } } function GetDotNetInstallScript([string] $dotnetRoot) { $installScript = Join-Path $dotnetRoot 'dotnet-install.ps1' if (!(Test-Path $installScript)) { Create-Directory $dotnetRoot $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit $uri = "https://dotnet.microsoft.com/download/dotnet/scripts/$dotnetInstallScriptVersion/dotnet-install.ps1" Retry({ Write-Host "GET $uri" Invoke-WebRequest $uri -OutFile $installScript }) } return $installScript } function InstallDotNetSdk([string] $dotnetRoot, [string] $version, [string] $architecture = '', [switch] $noPath) { InstallDotNet $dotnetRoot $version $architecture '' $false $runtimeSourceFeed $runtimeSourceFeedKey -noPath:$noPath } function InstallDotNet([string] $dotnetRoot, [string] $version, [string] $architecture = '', [string] $runtime = '', [bool] $skipNonVersionedFiles = $false, [string] $runtimeSourceFeed = '', [string] $runtimeSourceFeedKey = '', [switch] $noPath) { $installScript = GetDotNetInstallScript $dotnetRoot $installParameters = @{ Version = $version InstallDir = $dotnetRoot } if ($architecture) { $installParameters.Architecture = $architecture } if ($runtime) { $installParameters.Runtime = $runtime } if ($skipNonVersionedFiles) { $installParameters.SkipNonVersionedFiles = $skipNonVersionedFiles } if ($noPath) { $installParameters.NoPath = $True } try { & $installScript @installParameters } catch { if ($runtimeSourceFeed -or $runtimeSourceFeedKey) { Write-Host "Failed to install dotnet from public location. Trying from '$runtimeSourceFeed'" if ($runtimeSourceFeed) { $installParameters.AzureFeed = $runtimeSourceFeed } if ($runtimeSourceFeedKey) { $decodedBytes = [System.Convert]::FromBase64String($runtimeSourceFeedKey) $decodedString = [System.Text.Encoding]::UTF8.GetString($decodedBytes) $installParameters.FeedCredential = $decodedString } try { & $installScript @installParameters } catch { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Failed to install dotnet from custom location '$runtimeSourceFeed'." ExitWithExitCode 1 } } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Failed to install dotnet from public location." ExitWithExitCode 1 } } } # # Locates Visual Studio MSBuild installation. # The preference order for MSBuild to use is as follows: # # 1. MSBuild from an active VS command prompt # 2. MSBuild from a compatible VS installation # 3. MSBuild from the xcopy tool package # # Returns full path to msbuild.exe. # Throws on failure. # function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = $null) { if (-not (IsWindowsPlatform)) { throw "Cannot initialize Visual Studio on non-Windows" } if (Test-Path variable:global:_MSBuildExe) { return $global:_MSBuildExe } # Minimum VS version to require. $vsMinVersionReqdStr = '16.8' $vsMinVersionReqd = [Version]::new($vsMinVersionReqdStr) # If the version of msbuild is going to be xcopied, # use this version. Version matches a package here: # https://dev.azure.com/dnceng/public/_packaging?_a=package&feed=dotnet-eng&package=RoslynTools.MSBuild&protocolType=NuGet&version=16.10.0-preview2&view=overview $defaultXCopyMSBuildVersion = '16.10.0-preview2' if (!$vsRequirements) { $vsRequirements = $GlobalJson.tools.vs } $vsMinVersionStr = if ($vsRequirements.version) { $vsRequirements.version } else { $vsMinVersionReqdStr } $vsMinVersion = [Version]::new($vsMinVersionStr) # Try msbuild command available in the environment. if ($env:VSINSTALLDIR -ne $null) { $msbuildCmd = Get-Command 'msbuild.exe' -ErrorAction SilentlyContinue if ($msbuildCmd -ne $null) { # Workaround for https://github.com/dotnet/roslyn/issues/35793 # Due to this issue $msbuildCmd.Version returns 0.0.0.0 for msbuild.exe 16.2+ $msbuildVersion = [Version]::new((Get-Item $msbuildCmd.Path).VersionInfo.ProductVersion.Split([char[]]@('-', '+'))[0]) if ($msbuildVersion -ge $vsMinVersion) { return $global:_MSBuildExe = $msbuildCmd.Path } # Report error - the developer environment is initialized with incompatible VS version. throw "Developer Command Prompt for VS $($env:VisualStudioVersion) is not recent enough. Please upgrade to $vsMinVersionStr or build from a plain CMD window" } } # Locate Visual Studio installation or download x-copy msbuild. $vsInfo = LocateVisualStudio $vsRequirements if ($vsInfo -ne $null) { $vsInstallDir = $vsInfo.installationPath $vsMajorVersion = $vsInfo.installationVersion.Split('.')[0] InitializeVisualStudioEnvironmentVariables $vsInstallDir $vsMajorVersion } else { if (Get-Member -InputObject $GlobalJson.tools -Name 'xcopy-msbuild') { $xcopyMSBuildVersion = $GlobalJson.tools.'xcopy-msbuild' $vsMajorVersion = $xcopyMSBuildVersion.Split('.')[0] } else { #if vs version provided in global.json is incompatible (too low) then use the default version for xcopy msbuild download if($vsMinVersion -lt $vsMinVersionReqd){ Write-Host "Using xcopy-msbuild version of $defaultXCopyMSBuildVersion since VS version $vsMinVersionStr provided in global.json is not compatible" $xcopyMSBuildVersion = $defaultXCopyMSBuildVersion } else{ # If the VS version IS compatible, look for an xcopy msbuild package # with a version matching VS. # Note: If this version does not exist, then an explicit version of xcopy msbuild # can be specified in global.json. This will be required for pre-release versions of msbuild. $vsMajorVersion = $vsMinVersion.Major $vsMinorVersion = $vsMinVersion.Minor $xcopyMSBuildVersion = "$vsMajorVersion.$vsMinorVersion.0" } } $vsInstallDir = $null if ($xcopyMSBuildVersion.Trim() -ine "none") { $vsInstallDir = InitializeXCopyMSBuild $xcopyMSBuildVersion $install if ($vsInstallDir -eq $null) { throw "Could not xcopy msbuild. Please check that package 'RoslynTools.MSBuild @ $xcopyMSBuildVersion' exists on feed 'dotnet-eng'." } } if ($vsInstallDir -eq $null) { throw 'Unable to find Visual Studio that has required version and components installed' } } $msbuildVersionDir = if ([int]$vsMajorVersion -lt 16) { "$vsMajorVersion.0" } else { "Current" } $local:BinFolder = Join-Path $vsInstallDir "MSBuild\$msbuildVersionDir\Bin" $local:Prefer64bit = if (Get-Member -InputObject $vsRequirements -Name 'Prefer64bit') { $vsRequirements.Prefer64bit } else { $false } if ($local:Prefer64bit -and (Test-Path(Join-Path $local:BinFolder "amd64"))) { $global:_MSBuildExe = Join-Path $local:BinFolder "amd64\msbuild.exe" } else { $global:_MSBuildExe = Join-Path $local:BinFolder "msbuild.exe" } return $global:_MSBuildExe } function InitializeVisualStudioEnvironmentVariables([string] $vsInstallDir, [string] $vsMajorVersion) { $env:VSINSTALLDIR = $vsInstallDir Set-Item "env:VS$($vsMajorVersion)0COMNTOOLS" (Join-Path $vsInstallDir "Common7\Tools\") $vsSdkInstallDir = Join-Path $vsInstallDir "VSSDK\" if (Test-Path $vsSdkInstallDir) { Set-Item "env:VSSDK$($vsMajorVersion)0Install" $vsSdkInstallDir $env:VSSDKInstall = $vsSdkInstallDir } } function InstallXCopyMSBuild([string]$packageVersion) { return InitializeXCopyMSBuild $packageVersion -install $true } function InitializeXCopyMSBuild([string]$packageVersion, [bool]$install) { $packageName = 'RoslynTools.MSBuild' $packageDir = Join-Path $ToolsDir "msbuild\$packageVersion" $packagePath = Join-Path $packageDir "$packageName.$packageVersion.nupkg" if (!(Test-Path $packageDir)) { if (!$install) { return $null } Create-Directory $packageDir Write-Host "Downloading $packageName $packageVersion" $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit Retry({ Invoke-WebRequest "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/flat2/$packageName/$packageVersion/$packageName.$packageVersion.nupkg" -OutFile $packagePath }) Unzip $packagePath $packageDir } return Join-Path $packageDir 'tools' } # # Locates Visual Studio instance that meets the minimal requirements specified by tools.vs object in global.json. # # The following properties of tools.vs are recognized: # "version": "{major}.{minor}" # Two part minimal VS version, e.g. "15.9", "16.0", etc. # "components": ["componentId1", "componentId2", ...] # Array of ids of workload components that must be available in the VS instance. # See e.g. https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-enterprise?view=vs-2017 # # Returns JSON describing the located VS instance (same format as returned by vswhere), # or $null if no instance meeting the requirements is found on the machine. # function LocateVisualStudio([object]$vsRequirements = $null){ if (-not (IsWindowsPlatform)) { throw "Cannot run vswhere on non-Windows platforms." } if (Get-Member -InputObject $GlobalJson.tools -Name 'vswhere') { $vswhereVersion = $GlobalJson.tools.vswhere } else { $vswhereVersion = '2.5.2' } $vsWhereDir = Join-Path $ToolsDir "vswhere\$vswhereVersion" $vsWhereExe = Join-Path $vsWhereDir 'vswhere.exe' if (!(Test-Path $vsWhereExe)) { Create-Directory $vsWhereDir Write-Host 'Downloading vswhere' Retry({ Invoke-WebRequest "https://netcorenativeassets.blob.core.windows.net/resource-packages/external/windows/vswhere/$vswhereVersion/vswhere.exe" -OutFile $vswhereExe }) } if (!$vsRequirements) { $vsRequirements = $GlobalJson.tools.vs } $args = @('-latest', '-format', 'json', '-requires', 'Microsoft.Component.MSBuild', '-products', '*') if (!$excludePrereleaseVS) { $args += '-prerelease' } if (Get-Member -InputObject $vsRequirements -Name 'version') { $args += '-version' $args += $vsRequirements.version } if (Get-Member -InputObject $vsRequirements -Name 'components') { foreach ($component in $vsRequirements.components) { $args += '-requires' $args += $component } } $vsInfo =& $vsWhereExe $args | ConvertFrom-Json if ($lastExitCode -ne 0) { return $null } # use first matching instance return $vsInfo[0] } function InitializeBuildTool() { if (Test-Path variable:global:_BuildTool) { # If the requested msbuild parameters do not match, clear the cached variables. if($global:_BuildTool.Contains('ExcludePrereleaseVS') -and $global:_BuildTool.ExcludePrereleaseVS -ne $excludePrereleaseVS) { Remove-Item variable:global:_BuildTool Remove-Item variable:global:_MSBuildExe } else { return $global:_BuildTool } } if (-not $msbuildEngine) { $msbuildEngine = GetDefaultMSBuildEngine } # Initialize dotnet cli if listed in 'tools' $dotnetRoot = $null if (Get-Member -InputObject $GlobalJson.tools -Name 'dotnet') { $dotnetRoot = InitializeDotNetCli -install:$restore } if ($msbuildEngine -eq 'dotnet') { if (!$dotnetRoot) { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "/global.json must specify 'tools.dotnet'." ExitWithExitCode 1 } $dotnetPath = Join-Path $dotnetRoot (GetExecutableFileName 'dotnet') $buildTool = @{ Path = $dotnetPath; Command = 'msbuild'; Tool = 'dotnet'; Framework = 'netcoreapp3.1' } } elseif ($msbuildEngine -eq "vs") { try { $msbuildPath = InitializeVisualStudioMSBuild -install:$restore } catch { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_ ExitWithExitCode 1 } $buildTool = @{ Path = $msbuildPath; Command = ""; Tool = "vs"; Framework = "net472"; ExcludePrereleaseVS = $excludePrereleaseVS } } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unexpected value of -msbuildEngine: '$msbuildEngine'." ExitWithExitCode 1 } return $global:_BuildTool = $buildTool } function GetDefaultMSBuildEngine() { # Presence of tools.vs indicates the repo needs to build using VS msbuild on Windows. if (Get-Member -InputObject $GlobalJson.tools -Name 'vs') { return 'vs' } if (Get-Member -InputObject $GlobalJson.tools -Name 'dotnet') { return 'dotnet' } Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "-msbuildEngine must be specified, or /global.json must specify 'tools.dotnet' or 'tools.vs'." ExitWithExitCode 1 } function GetNuGetPackageCachePath() { if ($env:NUGET_PACKAGES -eq $null) { # Use local cache on CI to ensure deterministic build. # Avoid using the http cache as workaround for https://github.com/NuGet/Home/issues/3116 # use global cache in dev builds to avoid cost of downloading packages. # For directory normalization, see also: https://github.com/NuGet/Home/issues/7968 if ($useGlobalNuGetCache) { $env:NUGET_PACKAGES = Join-Path $env:UserProfile '.nuget\packages\' } else { $env:NUGET_PACKAGES = Join-Path $RepoRoot '.packages\' $env:RESTORENOCACHE = $true } } return $env:NUGET_PACKAGES } # Returns a full path to an Arcade SDK task project file. function GetSdkTaskProject([string]$taskName) { return Join-Path (Split-Path (InitializeToolset) -Parent) "SdkTasks\$taskName.proj" } function InitializeNativeTools() { if (-Not (Test-Path variable:DisableNativeToolsetInstalls) -And (Get-Member -InputObject $GlobalJson -Name "native-tools")) { $nativeArgs= @{} if ($ci) { $nativeArgs = @{ InstallDirectory = "$ToolsDir" } } & "$PSScriptRoot/init-tools-native.ps1" @nativeArgs } } function InitializeToolset() { if (Test-Path variable:global:_ToolsetBuildProj) { return $global:_ToolsetBuildProj } $nugetCache = GetNuGetPackageCachePath $toolsetVersion = $GlobalJson.'msbuild-sdks'.'Microsoft.DotNet.Arcade.Sdk' $toolsetLocationFile = Join-Path $ToolsetDir "$toolsetVersion.txt" if (Test-Path $toolsetLocationFile) { $path = Get-Content $toolsetLocationFile -TotalCount 1 if (Test-Path $path) { return $global:_ToolsetBuildProj = $path } } if (-not $restore) { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Toolset version $toolsetVersion has not been restored." ExitWithExitCode 1 } $buildTool = InitializeBuildTool $proj = Join-Path $ToolsetDir 'restore.proj' $bl = if ($binaryLog) { '/bl:' + (Join-Path $LogDir 'ToolsetRestore.binlog') } else { '' } '<Project Sdk="Microsoft.DotNet.Arcade.Sdk"/>' | Set-Content $proj MSBuild-Core $proj $bl /t:__WriteToolsetLocation /clp:ErrorsOnly`;NoSummary /p:__ToolsetLocationOutputFile=$toolsetLocationFile $path = Get-Content $toolsetLocationFile -Encoding UTF8 -TotalCount 1 if (!(Test-Path $path)) { throw "Invalid toolset path: $path" } return $global:_ToolsetBuildProj = $path } function ExitWithExitCode([int] $exitCode) { if ($ci -and $prepareMachine) { Stop-Processes } exit $exitCode } # Check if $LASTEXITCODE is a nonzero exit code (NZEC). If so, print a Azure Pipeline error for # diagnostics, then exit the script with the $LASTEXITCODE. function Exit-IfNZEC([string] $category = "General") { Write-Host "Exit code $LASTEXITCODE" if ($LASTEXITCODE -ne 0) { $message = "Last command failed with exit code $LASTEXITCODE." Write-PipelineTelemetryError -Force -Category $category -Message $message ExitWithExitCode $LASTEXITCODE } } function Stop-Processes() { Write-Host 'Killing running build processes...' foreach ($processName in $processesToStopOnExit) { Get-Process -Name $processName -ErrorAction SilentlyContinue | Stop-Process } } # # Executes msbuild (or 'dotnet msbuild') with arguments passed to the function. # The arguments are automatically quoted. # Terminates the script if the build fails. # function MSBuild() { if ($pipelinesLog) { $buildTool = InitializeBuildTool if ($ci -and $buildTool.Tool -eq 'dotnet') { $env:NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS = 20 $env:NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS = 20 Write-PipelineSetVariable -Name 'NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS' -Value '20' Write-PipelineSetVariable -Name 'NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS' -Value '20' } if ($ci) { $env:NUGET_ENABLE_EXPERIMENTAL_HTTP_RETRY = 'true' $env:NUGET_EXPERIMENTAL_MAX_NETWORK_TRY_COUNT = 6 $env:NUGET_EXPERIMENTAL_NETWORK_RETRY_DELAY_MILLISECONDS = 1000 Write-PipelineSetVariable -Name 'NUGET_ENABLE_EXPERIMENTAL_HTTP_RETRY' -Value 'true' Write-PipelineSetVariable -Name 'NUGET_EXPERIMENTAL_MAX_NETWORK_TRY_COUNT' -Value '6' Write-PipelineSetVariable -Name 'NUGET_EXPERIMENTAL_NETWORK_RETRY_DELAY_MILLISECONDS' -Value '1000' } $toolsetBuildProject = InitializeToolset $basePath = Split-Path -parent $toolsetBuildProject $possiblePaths = @( # new scripts need to work with old packages, so we need to look for the old names/versions (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.Arcade.Sdk.dll')), (Join-Path $basePath (Join-Path netcoreapp2.1 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path netcoreapp2.1 'Microsoft.DotNet.Arcade.Sdk.dll')) (Join-Path $basePath (Join-Path netcoreapp3.1 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path netcoreapp3.1 'Microsoft.DotNet.Arcade.Sdk.dll')) ) $selectedPath = $null foreach ($path in $possiblePaths) { if (Test-Path $path -PathType Leaf) { $selectedPath = $path break } } if (-not $selectedPath) { Write-PipelineTelemetryError -Category 'Build' -Message 'Unable to find arcade sdk logger assembly.' ExitWithExitCode 1 } $args += "/logger:$selectedPath" } MSBuild-Core @args } # # Executes msbuild (or 'dotnet msbuild') with arguments passed to the function. # The arguments are automatically quoted. # Terminates the script if the build fails. # function MSBuild-Core() { if ($ci) { if (!$binaryLog -and !$excludeCIBinarylog) { Write-PipelineTelemetryError -Category 'Build' -Message 'Binary log must be enabled in CI build, or explicitly opted-out from with the -excludeCIBinarylog switch.' ExitWithExitCode 1 } if ($nodeReuse) { Write-PipelineTelemetryError -Category 'Build' -Message 'Node reuse must be disabled in CI build.' ExitWithExitCode 1 } } $buildTool = InitializeBuildTool $cmdArgs = "$($buildTool.Command) /m /nologo /clp:Summary /v:$verbosity /nr:$nodeReuse /p:ContinuousIntegrationBuild=$ci" if ($warnAsError) { $cmdArgs += ' /warnaserror /p:TreatWarningsAsErrors=true' } else { $cmdArgs += ' /p:TreatWarningsAsErrors=false' } foreach ($arg in $args) { if ($null -ne $arg -and $arg.Trim() -ne "") { if ($arg.EndsWith('\')) { $arg = $arg + "\" } $cmdArgs += " `"$arg`"" } } $env:ARCADE_BUILD_TOOL_COMMAND = "$($buildTool.Path) $cmdArgs" $exitCode = Exec-Process $buildTool.Path $cmdArgs if ($exitCode -ne 0) { # We should not Write-PipelineTaskError here because that message shows up in the build summary # The build already logged an error, that's the reason it failed. Producing an error here only adds noise. Write-Host "Build failed with exit code $exitCode. Check errors above." -ForegroundColor Red $buildLog = GetMSBuildBinaryLogCommandLineArgument $args if ($null -ne $buildLog) { Write-Host "See log: $buildLog" -ForegroundColor DarkGray } if ($ci) { Write-PipelineSetResult -Result "Failed" -Message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error ExitWithExitCode 0 } else { ExitWithExitCode $exitCode } } } function GetMSBuildBinaryLogCommandLineArgument($arguments) { foreach ($argument in $arguments) { if ($argument -ne $null) { $arg = $argument.Trim() if ($arg.StartsWith('/bl:', "OrdinalIgnoreCase")) { return $arg.Substring('/bl:'.Length) } if ($arg.StartsWith('/binaryLogger:', 'OrdinalIgnoreCase')) { return $arg.Substring('/binaryLogger:'.Length) } } } return $null } function GetExecutableFileName($baseName) { if (IsWindowsPlatform) { return "$baseName.exe" } else { return $baseName } } function IsWindowsPlatform() { return [environment]::OSVersion.Platform -eq [PlatformID]::Win32NT } function Get-Darc($version) { $darcPath = "$TempDir\darc\$(New-Guid)" if ($version -ne $null) { & $PSScriptRoot\darc-init.ps1 -toolpath $darcPath -darcVersion $version | Out-Host } else { & $PSScriptRoot\darc-init.ps1 -toolpath $darcPath | Out-Host } return "$darcPath\darc.exe" } . $PSScriptRoot\pipeline-logging-functions.ps1 $RepoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\..\') $EngRoot = Resolve-Path (Join-Path $PSScriptRoot '..') $ArtifactsDir = Join-Path $RepoRoot 'artifacts' $ToolsetDir = Join-Path $ArtifactsDir 'toolset' $ToolsDir = Join-Path $RepoRoot '.tools' $LogDir = Join-Path (Join-Path $ArtifactsDir 'log') $configuration $TempDir = Join-Path (Join-Path $ArtifactsDir 'tmp') $configuration $GlobalJson = Get-Content -Raw -Path (Join-Path $RepoRoot 'global.json') | ConvertFrom-Json # true if global.json contains a "runtimes" section $globalJsonHasRuntimes = if ($GlobalJson.tools.PSObject.Properties.Name -Match 'runtimes') { $true } else { $false } Create-Directory $ToolsetDir Create-Directory $TempDir Create-Directory $LogDir Write-PipelineSetVariable -Name 'Artifacts' -Value $ArtifactsDir Write-PipelineSetVariable -Name 'Artifacts.Toolset' -Value $ToolsetDir Write-PipelineSetVariable -Name 'Artifacts.Log' -Value $LogDir Write-PipelineSetVariable -Name 'TEMP' -Value $TempDir Write-PipelineSetVariable -Name 'TMP' -Value $TempDir # Import custom tools configuration, if present in the repo. # Note: Import in global scope so that the script set top-level variables without qualification. if (!$disableConfigureToolsetImport) { $configureToolsetScript = Join-Path $EngRoot 'configure-toolset.ps1' if (Test-Path $configureToolsetScript) { . $configureToolsetScript if ((Test-Path variable:failOnConfigureToolsetError) -And $failOnConfigureToolsetError) { if ((Test-Path variable:LastExitCode) -And ($LastExitCode -ne 0)) { Write-PipelineTelemetryError -Category 'Build' -Message 'configure-toolset.ps1 returned a non-zero exit code' ExitWithExitCode $LastExitCode } } } } function Try-LogClientIpAddress() { Write-Host "Attempting to log this client's IP for Azure Package feed telemetry purposes" try { $result = Invoke-WebRequest -Uri "http://co1.msedge.net/fdv2/diagnostics.aspx" -UseBasicParsing $lines = $result.Content.Split([Environment]::NewLine) $socketIp = $lines | Select-String -Pattern "^Socket IP:.*" Write-Host $socketIp $clientIp = $lines | Select-String -Pattern "^Client IP:.*" Write-Host $clientIp } catch { Write-Host "Unable to get this machine's effective IP address for logging: $_" } }
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/tools.sh
#!/usr/bin/env bash # Initialize variables if they aren't already defined. # CI mode - set to true on CI server for PR validation build or official build. ci=${ci:-false} # Set to true to use the pipelines logger which will enable Azure logging output. # https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md # This flag is meant as a temporary opt-opt for the feature while validate it across # our consumers. It will be deleted in the future. if [[ "$ci" == true ]]; then pipelines_log=${pipelines_log:-true} else pipelines_log=${pipelines_log:-false} fi # Build configuration. Common values include 'Debug' and 'Release', but the repository may use other names. configuration=${configuration:-'Debug'} # Set to true to opt out of outputting binary log while running in CI exclude_ci_binary_log=${exclude_ci_binary_log:-false} if [[ "$ci" == true && "$exclude_ci_binary_log" == false ]]; then binary_log_default=true else binary_log_default=false fi # Set to true to output binary log from msbuild. Note that emitting binary log slows down the build. binary_log=${binary_log:-$binary_log_default} # Turns on machine preparation/clean up code that changes the machine state (e.g. kills build processes). prepare_machine=${prepare_machine:-false} # True to restore toolsets and dependencies. restore=${restore:-true} # Adjusts msbuild verbosity level. verbosity=${verbosity:-'minimal'} # Set to true to reuse msbuild nodes. Recommended to not reuse on CI. if [[ "$ci" == true ]]; then node_reuse=${node_reuse:-false} else node_reuse=${node_reuse:-true} fi # Configures warning treatment in msbuild. warn_as_error=${warn_as_error:-true} # True to attempt using .NET Core already that meets requirements specified in global.json # installed on the machine instead of downloading one. use_installed_dotnet_cli=${use_installed_dotnet_cli:-true} # Enable repos to use a particular version of the on-line dotnet-install scripts. # default URL: https://dotnet.microsoft.com/download/dotnet/scripts/v1/dotnet-install.sh dotnetInstallScriptVersion=${dotnetInstallScriptVersion:-'v1'} # True to use global NuGet cache instead of restoring packages to repository-local directory. if [[ "$ci" == true ]]; then use_global_nuget_cache=${use_global_nuget_cache:-false} else use_global_nuget_cache=${use_global_nuget_cache:-true} fi # Used when restoring .NET SDK from alternative feeds runtime_source_feed=${runtime_source_feed:-''} runtime_source_feed_key=${runtime_source_feed_key:-''} # Resolve any symlinks in the given path. function ResolvePath { local path=$1 while [[ -h $path ]]; do local dir="$( cd -P "$( dirname "$path" )" && pwd )" path="$(readlink "$path")" # if $path was a relative symlink, we need to resolve it relative to the path where the # symlink file was located [[ $path != /* ]] && path="$dir/$path" done # return value _ResolvePath="$path" } # ReadVersionFromJson [json key] function ReadGlobalVersion { local key=$1 if command -v jq &> /dev/null; then _ReadGlobalVersion="$(jq -r ".[] | select(has(\"$key\")) | .\"$key\"" "$global_json_file")" elif [[ "$(cat "$global_json_file")" =~ \"$key\"[[:space:]\:]*\"([^\"]+) ]]; then _ReadGlobalVersion=${BASH_REMATCH[1]} fi if [[ -z "$_ReadGlobalVersion" ]]; then Write-PipelineTelemetryError -category 'Build' "Error: Cannot find \"$key\" in $global_json_file" ExitWithExitCode 1 fi } function InitializeDotNetCli { if [[ -n "${_InitializeDotNetCli:-}" ]]; then return fi local install=$1 # Don't resolve runtime, shared framework, or SDK from other locations to ensure build determinism export DOTNET_MULTILEVEL_LOOKUP=0 # Disable first run since we want to control all package sources export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 # Disable telemetry on CI if [[ $ci == true ]]; then export DOTNET_CLI_TELEMETRY_OPTOUT=1 fi # LTTNG is the logging infrastructure used by Core CLR. Need this variable set # so it doesn't output warnings to the console. export LTTNG_HOME="$HOME" # Source Build uses DotNetCoreSdkDir variable if [[ -n "${DotNetCoreSdkDir:-}" ]]; then export DOTNET_INSTALL_DIR="$DotNetCoreSdkDir" fi # Find the first path on $PATH that contains the dotnet.exe if [[ "$use_installed_dotnet_cli" == true && $global_json_has_runtimes == false && -z "${DOTNET_INSTALL_DIR:-}" ]]; then local dotnet_path=`command -v dotnet` if [[ -n "$dotnet_path" ]]; then ResolvePath "$dotnet_path" export DOTNET_INSTALL_DIR=`dirname "$_ResolvePath"` fi fi ReadGlobalVersion "dotnet" local dotnet_sdk_version=$_ReadGlobalVersion local dotnet_root="" # Use dotnet installation specified in DOTNET_INSTALL_DIR if it contains the required SDK version, # otherwise install the dotnet CLI and SDK to repo local .dotnet directory to avoid potential permission issues. if [[ $global_json_has_runtimes == false && -n "${DOTNET_INSTALL_DIR:-}" && -d "$DOTNET_INSTALL_DIR/sdk/$dotnet_sdk_version" ]]; then dotnet_root="$DOTNET_INSTALL_DIR" else dotnet_root="$repo_root/.dotnet" export DOTNET_INSTALL_DIR="$dotnet_root" if [[ ! -d "$DOTNET_INSTALL_DIR/sdk/$dotnet_sdk_version" ]]; then if [[ "$install" == true ]]; then InstallDotNetSdk "$dotnet_root" "$dotnet_sdk_version" else Write-PipelineTelemetryError -category 'InitializeToolset' "Unable to find dotnet with SDK version '$dotnet_sdk_version'" ExitWithExitCode 1 fi fi fi # Add dotnet to PATH. This prevents any bare invocation of dotnet in custom # build steps from using anything other than what we've downloaded. Write-PipelinePrependPath -path "$dotnet_root" Write-PipelineSetVariable -name "DOTNET_MULTILEVEL_LOOKUP" -value "0" Write-PipelineSetVariable -name "DOTNET_SKIP_FIRST_TIME_EXPERIENCE" -value "1" # return value _InitializeDotNetCli="$dotnet_root" } function InstallDotNetSdk { local root=$1 local version=$2 local architecture="unset" if [[ $# -ge 3 ]]; then architecture=$3 fi InstallDotNet "$root" "$version" $architecture 'sdk' 'false' $runtime_source_feed $runtime_source_feed_key } function InstallDotNet { local root=$1 local version=$2 GetDotNetInstallScript "$root" local install_script=$_GetDotNetInstallScript local archArg='' if [[ -n "${3:-}" ]] && [ "$3" != 'unset' ]; then archArg="--architecture $3" fi local runtimeArg='' if [[ -n "${4:-}" ]] && [ "$4" != 'sdk' ]; then runtimeArg="--runtime $4" fi local skipNonVersionedFilesArg="" if [[ "$#" -ge "5" ]] && [[ "$5" != 'false' ]]; then skipNonVersionedFilesArg="--skip-non-versioned-files" fi bash "$install_script" --version $version --install-dir "$root" $archArg $runtimeArg $skipNonVersionedFilesArg || { local exit_code=$? echo "Failed to install dotnet SDK from public location (exit code '$exit_code')." local runtimeSourceFeed='' if [[ -n "${6:-}" ]]; then runtimeSourceFeed="--azure-feed $6" fi local runtimeSourceFeedKey='' if [[ -n "${7:-}" ]]; then # The 'base64' binary on alpine uses '-d' and doesn't support '--decode' # '-d'. To work around this, do a simple detection and switch the parameter # accordingly. decodeArg="--decode" if base64 --help 2>&1 | grep -q "BusyBox"; then decodeArg="-d" fi decodedFeedKey=`echo $7 | base64 $decodeArg` runtimeSourceFeedKey="--feed-credential $decodedFeedKey" fi if [[ -n "$runtimeSourceFeed" || -n "$runtimeSourceFeedKey" ]]; then bash "$install_script" --version $version --install-dir "$root" $archArg $runtimeArg $skipNonVersionedFilesArg $runtimeSourceFeed $runtimeSourceFeedKey || { local exit_code=$? Write-PipelineTelemetryError -category 'InitializeToolset' "Failed to install dotnet SDK from custom location '$runtimeSourceFeed' (exit code '$exit_code')." ExitWithExitCode $exit_code } else if [[ $exit_code != 0 ]]; then Write-PipelineTelemetryError -category 'InitializeToolset' "Failed to install dotnet SDK from public location (exit code '$exit_code')." fi ExitWithExitCode $exit_code fi } } function with_retries { local maxRetries=5 local retries=1 echo "Trying to run '$@' for maximum of $maxRetries attempts." while [[ $((retries++)) -le $maxRetries ]]; do "$@" if [[ $? == 0 ]]; then echo "Ran '$@' successfully." return 0 fi timeout=$((3**$retries-1)) echo "Failed to execute '$@'. Waiting $timeout seconds before next attempt ($retries out of $maxRetries)." 1>&2 sleep $timeout done echo "Failed to execute '$@' for $maxRetries times." 1>&2 return 1 } function GetDotNetInstallScript { local root=$1 local install_script="$root/dotnet-install.sh" local install_script_url="https://dotnet.microsoft.com/download/dotnet/scripts/$dotnetInstallScriptVersion/dotnet-install.sh" if [[ ! -a "$install_script" ]]; then mkdir -p "$root" echo "Downloading '$install_script_url'" # Use curl if available, otherwise use wget if command -v curl > /dev/null; then # first, try directly, if this fails we will retry with verbose logging curl "$install_script_url" -sSL --retry 10 --create-dirs -o "$install_script" || { if command -v openssl &> /dev/null; then echo "Curl failed; dumping some information about dotnet.microsoft.com for later investigation" echo | openssl s_client -showcerts -servername dotnet.microsoft.com -connect dotnet.microsoft.com:443 fi echo "Will now retry the same URL with verbose logging." with_retries curl "$install_script_url" -sSL --verbose --retry 10 --create-dirs -o "$install_script" || { local exit_code=$? Write-PipelineTelemetryError -category 'InitializeToolset' "Failed to acquire dotnet install script (exit code '$exit_code')." ExitWithExitCode $exit_code } } else with_retries wget -v -O "$install_script" "$install_script_url" || { local exit_code=$? Write-PipelineTelemetryError -category 'InitializeToolset' "Failed to acquire dotnet install script (exit code '$exit_code')." ExitWithExitCode $exit_code } fi fi # return value _GetDotNetInstallScript="$install_script" } function InitializeBuildTool { if [[ -n "${_InitializeBuildTool:-}" ]]; then return fi InitializeDotNetCli $restore # return values _InitializeBuildTool="$_InitializeDotNetCli/dotnet" _InitializeBuildToolCommand="msbuild" _InitializeBuildToolFramework="netcoreapp3.1" } # Set RestoreNoCache as a workaround for https://github.com/NuGet/Home/issues/3116 function GetNuGetPackageCachePath { if [[ -z ${NUGET_PACKAGES:-} ]]; then if [[ "$use_global_nuget_cache" == true ]]; then export NUGET_PACKAGES="$HOME/.nuget/packages" else export NUGET_PACKAGES="$repo_root/.packages" export RESTORENOCACHE=true fi fi # return value _GetNuGetPackageCachePath=$NUGET_PACKAGES } function InitializeNativeTools() { if [[ -n "${DisableNativeToolsetInstalls:-}" ]]; then return fi if grep -Fq "native-tools" $global_json_file then local nativeArgs="" if [[ "$ci" == true ]]; then nativeArgs="--installDirectory $tools_dir" fi "$_script_dir/init-tools-native.sh" $nativeArgs fi } function InitializeToolset { if [[ -n "${_InitializeToolset:-}" ]]; then return fi GetNuGetPackageCachePath ReadGlobalVersion "Microsoft.DotNet.Arcade.Sdk" local toolset_version=$_ReadGlobalVersion local toolset_location_file="$toolset_dir/$toolset_version.txt" if [[ -a "$toolset_location_file" ]]; then local path=`cat "$toolset_location_file"` if [[ -a "$path" ]]; then # return value _InitializeToolset="$path" return fi fi if [[ "$restore" != true ]]; then Write-PipelineTelemetryError -category 'InitializeToolset' "Toolset version $toolset_version has not been restored." ExitWithExitCode 2 fi local proj="$toolset_dir/restore.proj" local bl="" if [[ "$binary_log" == true ]]; then bl="/bl:$log_dir/ToolsetRestore.binlog" fi echo '<Project Sdk="Microsoft.DotNet.Arcade.Sdk"/>' > "$proj" MSBuild-Core "$proj" $bl /t:__WriteToolsetLocation /clp:ErrorsOnly\;NoSummary /p:__ToolsetLocationOutputFile="$toolset_location_file" local toolset_build_proj=`cat "$toolset_location_file"` if [[ ! -a "$toolset_build_proj" ]]; then Write-PipelineTelemetryError -category 'Build' "Invalid toolset path: $toolset_build_proj" ExitWithExitCode 3 fi # return value _InitializeToolset="$toolset_build_proj" } function ExitWithExitCode { if [[ "$ci" == true && "$prepare_machine" == true ]]; then StopProcesses fi exit $1 } function StopProcesses { echo "Killing running build processes..." pkill -9 "dotnet" || true pkill -9 "vbcscompiler" || true return 0 } function MSBuild { local args=$@ if [[ "$pipelines_log" == true ]]; then InitializeBuildTool InitializeToolset if [[ "$ci" == true ]]; then export NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS=20 export NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS=20 Write-PipelineSetVariable -name "NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS" -value "20" Write-PipelineSetVariable -name "NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS" -value "20" fi local toolset_dir="${_InitializeToolset%/*}" # new scripts need to work with old packages, so we need to look for the old names/versions local selectedPath= local possiblePaths=() possiblePaths+=( "$toolset_dir/$_InitializeBuildToolFramework/Microsoft.DotNet.ArcadeLogging.dll" ) possiblePaths+=( "$toolset_dir/$_InitializeBuildToolFramework/Microsoft.DotNet.Arcade.Sdk.dll" ) possiblePaths+=( "$toolset_dir/netcoreapp2.1/Microsoft.DotNet.ArcadeLogging.dll" ) possiblePaths+=( "$toolset_dir/netcoreapp2.1/Microsoft.DotNet.Arcade.Sdk.dll" ) for path in "${possiblePaths[@]}"; do if [[ -f $path ]]; then selectedPath=$path break fi done if [[ -z "$selectedPath" ]]; then Write-PipelineTelemetryError -category 'Build' "Unable to find arcade sdk logger assembly." ExitWithExitCode 1 fi args+=( "-logger:$selectedPath" ) fi MSBuild-Core ${args[@]} } function MSBuild-Core { if [[ "$ci" == true ]]; then if [[ "$binary_log" != true && "$exclude_ci_binary_log" != true ]]; then Write-PipelineTelemetryError -category 'Build' "Binary log must be enabled in CI build, or explicitly opted-out from with the -noBinaryLog switch." ExitWithExitCode 1 fi if [[ "$node_reuse" == true ]]; then Write-PipelineTelemetryError -category 'Build' "Node reuse must be disabled in CI build." ExitWithExitCode 1 fi fi InitializeBuildTool local warnaserror_switch="" if [[ $warn_as_error == true ]]; then warnaserror_switch="/warnaserror" fi function RunBuildTool { export ARCADE_BUILD_TOOL_COMMAND="$_InitializeBuildTool $@" "$_InitializeBuildTool" "$@" || { local exit_code=$? # We should not Write-PipelineTaskError here because that message shows up in the build summary # The build already logged an error, that's the reason it failed. Producing an error here only adds noise. echo "Build failed with exit code $exit_code. Check errors above." if [[ "$ci" == "true" ]]; then Write-PipelineSetResult -result "Failed" -message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error ExitWithExitCode 0 else ExitWithExitCode $exit_code fi } } RunBuildTool "$_InitializeBuildToolCommand" /m /nologo /clp:Summary /v:$verbosity /nr:$node_reuse $warnaserror_switch /p:TreatWarningsAsErrors=$warn_as_error /p:ContinuousIntegrationBuild=$ci "$@" } ResolvePath "${BASH_SOURCE[0]}" _script_dir=`dirname "$_ResolvePath"` . "$_script_dir/pipeline-logging-functions.sh" eng_root=`cd -P "$_script_dir/.." && pwd` repo_root=`cd -P "$_script_dir/../.." && pwd` repo_root="${repo_root}/" artifacts_dir="${repo_root}artifacts" toolset_dir="$artifacts_dir/toolset" tools_dir="${repo_root}.tools" log_dir="$artifacts_dir/log/$configuration" temp_dir="$artifacts_dir/tmp/$configuration" global_json_file="${repo_root}global.json" # determine if global.json contains a "runtimes" entry global_json_has_runtimes=false if command -v jq &> /dev/null; then if jq -er '. | select(has("runtimes"))' "$global_json_file" &> /dev/null; then global_json_has_runtimes=true fi elif [[ "$(cat "$global_json_file")" =~ \"runtimes\"[[:space:]\:]*\{ ]]; then global_json_has_runtimes=true fi # HOME may not be defined in some scenarios, but it is required by NuGet if [[ -z $HOME ]]; then export HOME="${repo_root}artifacts/.home/" mkdir -p "$HOME" fi mkdir -p "$toolset_dir" mkdir -p "$temp_dir" mkdir -p "$log_dir" Write-PipelineSetVariable -name "Artifacts" -value "$artifacts_dir" Write-PipelineSetVariable -name "Artifacts.Toolset" -value "$toolset_dir" Write-PipelineSetVariable -name "Artifacts.Log" -value "$log_dir" Write-PipelineSetVariable -name "Temp" -value "$temp_dir" Write-PipelineSetVariable -name "TMP" -value "$temp_dir" # Import custom tools configuration, if present in the repo. if [ -z "${disable_configure_toolset_import:-}" ]; then configure_toolset_script="$eng_root/configure-toolset.sh" if [[ -a "$configure_toolset_script" ]]; then . "$configure_toolset_script" fi fi # TODO: https://github.com/dotnet/arcade/issues/1468 # Temporary workaround to avoid breaking change. # Remove once repos are updated. if [[ -n "${useInstalledDotNetCli:-}" ]]; then use_installed_dotnet_cli="$useInstalledDotNetCli" fi
#!/usr/bin/env bash # Initialize variables if they aren't already defined. # CI mode - set to true on CI server for PR validation build or official build. ci=${ci:-false} # Set to true to use the pipelines logger which will enable Azure logging output. # https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md # This flag is meant as a temporary opt-opt for the feature while validate it across # our consumers. It will be deleted in the future. if [[ "$ci" == true ]]; then pipelines_log=${pipelines_log:-true} else pipelines_log=${pipelines_log:-false} fi # Build configuration. Common values include 'Debug' and 'Release', but the repository may use other names. configuration=${configuration:-'Debug'} # Set to true to opt out of outputting binary log while running in CI exclude_ci_binary_log=${exclude_ci_binary_log:-false} if [[ "$ci" == true && "$exclude_ci_binary_log" == false ]]; then binary_log_default=true else binary_log_default=false fi # Set to true to output binary log from msbuild. Note that emitting binary log slows down the build. binary_log=${binary_log:-$binary_log_default} # Turns on machine preparation/clean up code that changes the machine state (e.g. kills build processes). prepare_machine=${prepare_machine:-false} # True to restore toolsets and dependencies. restore=${restore:-true} # Adjusts msbuild verbosity level. verbosity=${verbosity:-'minimal'} # Set to true to reuse msbuild nodes. Recommended to not reuse on CI. if [[ "$ci" == true ]]; then node_reuse=${node_reuse:-false} else node_reuse=${node_reuse:-true} fi # Configures warning treatment in msbuild. warn_as_error=${warn_as_error:-true} # True to attempt using .NET Core already that meets requirements specified in global.json # installed on the machine instead of downloading one. use_installed_dotnet_cli=${use_installed_dotnet_cli:-true} # Enable repos to use a particular version of the on-line dotnet-install scripts. # default URL: https://dotnet.microsoft.com/download/dotnet/scripts/v1/dotnet-install.sh dotnetInstallScriptVersion=${dotnetInstallScriptVersion:-'v1'} # True to use global NuGet cache instead of restoring packages to repository-local directory. if [[ "$ci" == true ]]; then use_global_nuget_cache=${use_global_nuget_cache:-false} else use_global_nuget_cache=${use_global_nuget_cache:-true} fi # Used when restoring .NET SDK from alternative feeds runtime_source_feed=${runtime_source_feed:-''} runtime_source_feed_key=${runtime_source_feed_key:-''} # Resolve any symlinks in the given path. function ResolvePath { local path=$1 while [[ -h $path ]]; do local dir="$( cd -P "$( dirname "$path" )" && pwd )" path="$(readlink "$path")" # if $path was a relative symlink, we need to resolve it relative to the path where the # symlink file was located [[ $path != /* ]] && path="$dir/$path" done # return value _ResolvePath="$path" } # ReadVersionFromJson [json key] function ReadGlobalVersion { local key=$1 if command -v jq &> /dev/null; then _ReadGlobalVersion="$(jq -r ".[] | select(has(\"$key\")) | .\"$key\"" "$global_json_file")" elif [[ "$(cat "$global_json_file")" =~ \"$key\"[[:space:]\:]*\"([^\"]+) ]]; then _ReadGlobalVersion=${BASH_REMATCH[1]} fi if [[ -z "$_ReadGlobalVersion" ]]; then Write-PipelineTelemetryError -category 'Build' "Error: Cannot find \"$key\" in $global_json_file" ExitWithExitCode 1 fi } function InitializeDotNetCli { if [[ -n "${_InitializeDotNetCli:-}" ]]; then return fi local install=$1 # Don't resolve runtime, shared framework, or SDK from other locations to ensure build determinism export DOTNET_MULTILEVEL_LOOKUP=0 # Disable first run since we want to control all package sources export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 # Disable telemetry on CI if [[ $ci == true ]]; then export DOTNET_CLI_TELEMETRY_OPTOUT=1 fi # LTTNG is the logging infrastructure used by Core CLR. Need this variable set # so it doesn't output warnings to the console. export LTTNG_HOME="$HOME" # Source Build uses DotNetCoreSdkDir variable if [[ -n "${DotNetCoreSdkDir:-}" ]]; then export DOTNET_INSTALL_DIR="$DotNetCoreSdkDir" fi # Find the first path on $PATH that contains the dotnet.exe if [[ "$use_installed_dotnet_cli" == true && $global_json_has_runtimes == false && -z "${DOTNET_INSTALL_DIR:-}" ]]; then local dotnet_path=`command -v dotnet` if [[ -n "$dotnet_path" ]]; then ResolvePath "$dotnet_path" export DOTNET_INSTALL_DIR=`dirname "$_ResolvePath"` fi fi ReadGlobalVersion "dotnet" local dotnet_sdk_version=$_ReadGlobalVersion local dotnet_root="" # Use dotnet installation specified in DOTNET_INSTALL_DIR if it contains the required SDK version, # otherwise install the dotnet CLI and SDK to repo local .dotnet directory to avoid potential permission issues. if [[ $global_json_has_runtimes == false && -n "${DOTNET_INSTALL_DIR:-}" && -d "$DOTNET_INSTALL_DIR/sdk/$dotnet_sdk_version" ]]; then dotnet_root="$DOTNET_INSTALL_DIR" else dotnet_root="$repo_root/.dotnet" export DOTNET_INSTALL_DIR="$dotnet_root" if [[ ! -d "$DOTNET_INSTALL_DIR/sdk/$dotnet_sdk_version" ]]; then if [[ "$install" == true ]]; then InstallDotNetSdk "$dotnet_root" "$dotnet_sdk_version" else Write-PipelineTelemetryError -category 'InitializeToolset' "Unable to find dotnet with SDK version '$dotnet_sdk_version'" ExitWithExitCode 1 fi fi fi # Add dotnet to PATH. This prevents any bare invocation of dotnet in custom # build steps from using anything other than what we've downloaded. Write-PipelinePrependPath -path "$dotnet_root" Write-PipelineSetVariable -name "DOTNET_MULTILEVEL_LOOKUP" -value "0" Write-PipelineSetVariable -name "DOTNET_SKIP_FIRST_TIME_EXPERIENCE" -value "1" # return value _InitializeDotNetCli="$dotnet_root" } function InstallDotNetSdk { local root=$1 local version=$2 local architecture="unset" if [[ $# -ge 3 ]]; then architecture=$3 fi InstallDotNet "$root" "$version" $architecture 'sdk' 'false' $runtime_source_feed $runtime_source_feed_key } function InstallDotNet { local root=$1 local version=$2 GetDotNetInstallScript "$root" local install_script=$_GetDotNetInstallScript local archArg='' if [[ -n "${3:-}" ]] && [ "$3" != 'unset' ]; then archArg="--architecture $3" fi local runtimeArg='' if [[ -n "${4:-}" ]] && [ "$4" != 'sdk' ]; then runtimeArg="--runtime $4" fi local skipNonVersionedFilesArg="" if [[ "$#" -ge "5" ]] && [[ "$5" != 'false' ]]; then skipNonVersionedFilesArg="--skip-non-versioned-files" fi bash "$install_script" --version $version --install-dir "$root" $archArg $runtimeArg $skipNonVersionedFilesArg || { local exit_code=$? echo "Failed to install dotnet SDK from public location (exit code '$exit_code')." local runtimeSourceFeed='' if [[ -n "${6:-}" ]]; then runtimeSourceFeed="--azure-feed $6" fi local runtimeSourceFeedKey='' if [[ -n "${7:-}" ]]; then # The 'base64' binary on alpine uses '-d' and doesn't support '--decode' # '-d'. To work around this, do a simple detection and switch the parameter # accordingly. decodeArg="--decode" if base64 --help 2>&1 | grep -q "BusyBox"; then decodeArg="-d" fi decodedFeedKey=`echo $7 | base64 $decodeArg` runtimeSourceFeedKey="--feed-credential $decodedFeedKey" fi if [[ -n "$runtimeSourceFeed" || -n "$runtimeSourceFeedKey" ]]; then bash "$install_script" --version $version --install-dir "$root" $archArg $runtimeArg $skipNonVersionedFilesArg $runtimeSourceFeed $runtimeSourceFeedKey || { local exit_code=$? Write-PipelineTelemetryError -category 'InitializeToolset' "Failed to install dotnet SDK from custom location '$runtimeSourceFeed' (exit code '$exit_code')." ExitWithExitCode $exit_code } else if [[ $exit_code != 0 ]]; then Write-PipelineTelemetryError -category 'InitializeToolset' "Failed to install dotnet SDK from public location (exit code '$exit_code')." fi ExitWithExitCode $exit_code fi } } function with_retries { local maxRetries=5 local retries=1 echo "Trying to run '$@' for maximum of $maxRetries attempts." while [[ $((retries++)) -le $maxRetries ]]; do "$@" if [[ $? == 0 ]]; then echo "Ran '$@' successfully." return 0 fi timeout=$((3**$retries-1)) echo "Failed to execute '$@'. Waiting $timeout seconds before next attempt ($retries out of $maxRetries)." 1>&2 sleep $timeout done echo "Failed to execute '$@' for $maxRetries times." 1>&2 return 1 } function GetDotNetInstallScript { local root=$1 local install_script="$root/dotnet-install.sh" local install_script_url="https://dotnet.microsoft.com/download/dotnet/scripts/$dotnetInstallScriptVersion/dotnet-install.sh" if [[ ! -a "$install_script" ]]; then mkdir -p "$root" echo "Downloading '$install_script_url'" # Use curl if available, otherwise use wget if command -v curl > /dev/null; then # first, try directly, if this fails we will retry with verbose logging curl "$install_script_url" -sSL --retry 10 --create-dirs -o "$install_script" || { if command -v openssl &> /dev/null; then echo "Curl failed; dumping some information about dotnet.microsoft.com for later investigation" echo | openssl s_client -showcerts -servername dotnet.microsoft.com -connect dotnet.microsoft.com:443 fi echo "Will now retry the same URL with verbose logging." with_retries curl "$install_script_url" -sSL --verbose --retry 10 --create-dirs -o "$install_script" || { local exit_code=$? Write-PipelineTelemetryError -category 'InitializeToolset' "Failed to acquire dotnet install script (exit code '$exit_code')." ExitWithExitCode $exit_code } } else with_retries wget -v -O "$install_script" "$install_script_url" || { local exit_code=$? Write-PipelineTelemetryError -category 'InitializeToolset' "Failed to acquire dotnet install script (exit code '$exit_code')." ExitWithExitCode $exit_code } fi fi # return value _GetDotNetInstallScript="$install_script" } function InitializeBuildTool { if [[ -n "${_InitializeBuildTool:-}" ]]; then return fi InitializeDotNetCli $restore # return values _InitializeBuildTool="$_InitializeDotNetCli/dotnet" _InitializeBuildToolCommand="msbuild" _InitializeBuildToolFramework="netcoreapp3.1" } # Set RestoreNoCache as a workaround for https://github.com/NuGet/Home/issues/3116 function GetNuGetPackageCachePath { if [[ -z ${NUGET_PACKAGES:-} ]]; then if [[ "$use_global_nuget_cache" == true ]]; then export NUGET_PACKAGES="$HOME/.nuget/packages" else export NUGET_PACKAGES="$repo_root/.packages" export RESTORENOCACHE=true fi fi # return value _GetNuGetPackageCachePath=$NUGET_PACKAGES } function InitializeNativeTools() { if [[ -n "${DisableNativeToolsetInstalls:-}" ]]; then return fi if grep -Fq "native-tools" $global_json_file then local nativeArgs="" if [[ "$ci" == true ]]; then nativeArgs="--installDirectory $tools_dir" fi "$_script_dir/init-tools-native.sh" $nativeArgs fi } function InitializeToolset { if [[ -n "${_InitializeToolset:-}" ]]; then return fi GetNuGetPackageCachePath ReadGlobalVersion "Microsoft.DotNet.Arcade.Sdk" local toolset_version=$_ReadGlobalVersion local toolset_location_file="$toolset_dir/$toolset_version.txt" if [[ -a "$toolset_location_file" ]]; then local path=`cat "$toolset_location_file"` if [[ -a "$path" ]]; then # return value _InitializeToolset="$path" return fi fi if [[ "$restore" != true ]]; then Write-PipelineTelemetryError -category 'InitializeToolset' "Toolset version $toolset_version has not been restored." ExitWithExitCode 2 fi local proj="$toolset_dir/restore.proj" local bl="" if [[ "$binary_log" == true ]]; then bl="/bl:$log_dir/ToolsetRestore.binlog" fi echo '<Project Sdk="Microsoft.DotNet.Arcade.Sdk"/>' > "$proj" MSBuild-Core "$proj" $bl /t:__WriteToolsetLocation /clp:ErrorsOnly\;NoSummary /p:__ToolsetLocationOutputFile="$toolset_location_file" local toolset_build_proj=`cat "$toolset_location_file"` if [[ ! -a "$toolset_build_proj" ]]; then Write-PipelineTelemetryError -category 'Build' "Invalid toolset path: $toolset_build_proj" ExitWithExitCode 3 fi # return value _InitializeToolset="$toolset_build_proj" } function ExitWithExitCode { if [[ "$ci" == true && "$prepare_machine" == true ]]; then StopProcesses fi exit $1 } function StopProcesses { echo "Killing running build processes..." pkill -9 "dotnet" || true pkill -9 "vbcscompiler" || true return 0 } function TryLogClientIpAddress () { echo 'Attempting to log this client''s IP for Azure Package feed telemetry purposes' if command -v curl > /dev/null; then curl -s 'http://co1.msedge.net/fdv2/diagnostics.aspx' | grep ' IP: ' || true fi } function MSBuild { local args=$@ if [[ "$pipelines_log" == true ]]; then InitializeBuildTool InitializeToolset if [[ "$ci" == true ]]; then export NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS=20 export NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS=20 Write-PipelineSetVariable -name "NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS" -value "20" Write-PipelineSetVariable -name "NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS" -value "20" export NUGET_ENABLE_EXPERIMENTAL_HTTP_RETRY=true export NUGET_EXPERIMENTAL_MAX_NETWORK_TRY_COUNT=6 export NUGET_EXPERIMENTAL_NETWORK_RETRY_DELAY_MILLISECONDS=1000 Write-PipelineSetVariable -name "NUGET_ENABLE_EXPERIMENTAL_HTTP_RETRY" -value "true" Write-PipelineSetVariable -name "NUGET_EXPERIMENTAL_MAX_NETWORK_TRY_COUNT" -value "6" Write-PipelineSetVariable -name "NUGET_EXPERIMENTAL_NETWORK_RETRY_DELAY_MILLISECONDS" -value "1000" fi local toolset_dir="${_InitializeToolset%/*}" # new scripts need to work with old packages, so we need to look for the old names/versions local selectedPath= local possiblePaths=() possiblePaths+=( "$toolset_dir/$_InitializeBuildToolFramework/Microsoft.DotNet.ArcadeLogging.dll" ) possiblePaths+=( "$toolset_dir/$_InitializeBuildToolFramework/Microsoft.DotNet.Arcade.Sdk.dll" ) possiblePaths+=( "$toolset_dir/netcoreapp2.1/Microsoft.DotNet.ArcadeLogging.dll" ) possiblePaths+=( "$toolset_dir/netcoreapp2.1/Microsoft.DotNet.Arcade.Sdk.dll" ) possiblePaths+=( "$toolset_dir/netcoreapp3.1/Microsoft.DotNet.ArcadeLogging.dll" ) possiblePaths+=( "$toolset_dir/netcoreapp3.1/Microsoft.DotNet.Arcade.Sdk.dll" ) for path in "${possiblePaths[@]}"; do if [[ -f $path ]]; then selectedPath=$path break fi done if [[ -z "$selectedPath" ]]; then Write-PipelineTelemetryError -category 'Build' "Unable to find arcade sdk logger assembly." ExitWithExitCode 1 fi args+=( "-logger:$selectedPath" ) fi MSBuild-Core ${args[@]} } function MSBuild-Core { if [[ "$ci" == true ]]; then if [[ "$binary_log" != true && "$exclude_ci_binary_log" != true ]]; then Write-PipelineTelemetryError -category 'Build' "Binary log must be enabled in CI build, or explicitly opted-out from with the -noBinaryLog switch." ExitWithExitCode 1 fi if [[ "$node_reuse" == true ]]; then Write-PipelineTelemetryError -category 'Build' "Node reuse must be disabled in CI build." ExitWithExitCode 1 fi fi InitializeBuildTool local warnaserror_switch="" if [[ $warn_as_error == true ]]; then warnaserror_switch="/warnaserror" fi function RunBuildTool { export ARCADE_BUILD_TOOL_COMMAND="$_InitializeBuildTool $@" "$_InitializeBuildTool" "$@" || { local exit_code=$? # We should not Write-PipelineTaskError here because that message shows up in the build summary # The build already logged an error, that's the reason it failed. Producing an error here only adds noise. echo "Build failed with exit code $exit_code. Check errors above." if [[ "$ci" == "true" ]]; then Write-PipelineSetResult -result "Failed" -message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error ExitWithExitCode 0 else ExitWithExitCode $exit_code fi } } RunBuildTool "$_InitializeBuildToolCommand" /m /nologo /clp:Summary /v:$verbosity /nr:$node_reuse $warnaserror_switch /p:TreatWarningsAsErrors=$warn_as_error /p:ContinuousIntegrationBuild=$ci "$@" } ResolvePath "${BASH_SOURCE[0]}" _script_dir=`dirname "$_ResolvePath"` . "$_script_dir/pipeline-logging-functions.sh" eng_root=`cd -P "$_script_dir/.." && pwd` repo_root=`cd -P "$_script_dir/../.." && pwd` repo_root="${repo_root}/" artifacts_dir="${repo_root}artifacts" toolset_dir="$artifacts_dir/toolset" tools_dir="${repo_root}.tools" log_dir="$artifacts_dir/log/$configuration" temp_dir="$artifacts_dir/tmp/$configuration" global_json_file="${repo_root}global.json" # determine if global.json contains a "runtimes" entry global_json_has_runtimes=false if command -v jq &> /dev/null; then if jq -er '. | select(has("runtimes"))' "$global_json_file" &> /dev/null; then global_json_has_runtimes=true fi elif [[ "$(cat "$global_json_file")" =~ \"runtimes\"[[:space:]\:]*\{ ]]; then global_json_has_runtimes=true fi # HOME may not be defined in some scenarios, but it is required by NuGet if [[ -z $HOME ]]; then export HOME="${repo_root}artifacts/.home/" mkdir -p "$HOME" fi mkdir -p "$toolset_dir" mkdir -p "$temp_dir" mkdir -p "$log_dir" Write-PipelineSetVariable -name "Artifacts" -value "$artifacts_dir" Write-PipelineSetVariable -name "Artifacts.Toolset" -value "$toolset_dir" Write-PipelineSetVariable -name "Artifacts.Log" -value "$log_dir" Write-PipelineSetVariable -name "Temp" -value "$temp_dir" Write-PipelineSetVariable -name "TMP" -value "$temp_dir" # Import custom tools configuration, if present in the repo. if [ -z "${disable_configure_toolset_import:-}" ]; then configure_toolset_script="$eng_root/configure-toolset.sh" if [[ -a "$configure_toolset_script" ]]; then . "$configure_toolset_script" fi fi # TODO: https://github.com/dotnet/arcade/issues/1468 # Temporary workaround to avoid breaking change. # Remove once repos are updated. if [[ -n "${useInstalledDotNetCli:-}" ]]; then use_installed_dotnet_cli="$useInstalledDotNetCli" fi
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./global.json
{ "sdk": { "version": "6.0.100-preview.7.21379.14", "allowPrerelease": true, "rollForward": "major" }, "tools": { "dotnet": "6.0.100-preview.7.21379.14", "vs": { "version": "16.10" }, "xcopy-msbuild": "16.10.0-preview2" }, "msbuild-sdks": { "Microsoft.DotNet.Arcade.Sdk": "6.0.0-beta.21413.4", "Microsoft.DotNet.Helix.Sdk": "6.0.0-beta.21413.4" } }
{ "sdk": { "version": "6.0.100-preview.7.21379.14", "allowPrerelease": true, "rollForward": "major" }, "tools": { "dotnet": "6.0.100-preview.7.21379.14", "vs": { "version": "16.10" }, "xcopy-msbuild": "16.10.0-preview2" }, "msbuild-sdks": { "Microsoft.DotNet.Arcade.Sdk": "7.0.0-beta.21463.4", "Microsoft.DotNet.Helix.Sdk": "7.0.0-beta.21463.4" } }
1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/build.ps1
[CmdletBinding(PositionalBinding=$false)] Param( [string][Alias('c')]$configuration = "Debug", [string]$platform = $null, [string] $projects, [string][Alias('v')]$verbosity = "minimal", [string] $msbuildEngine = $null, [bool] $warnAsError = $true, [bool] $nodeReuse = $true, [switch][Alias('r')]$restore, [switch] $deployDeps, [switch][Alias('b')]$build, [switch] $rebuild, [switch] $deploy, [switch][Alias('t')]$test, [switch] $integrationTest, [switch] $performanceTest, [switch] $sign, [switch] $pack, [switch] $publish, [switch] $clean, [switch][Alias('bl')]$binaryLog, [switch][Alias('nobl')]$excludeCIBinarylog, [switch] $ci, [switch] $prepareMachine, [string] $runtimeSourceFeed = '', [string] $runtimeSourceFeedKey = '', [switch] $excludePrereleaseVS, [switch] $help, [Parameter(ValueFromRemainingArguments=$true)][String[]]$properties ) # Unset 'Platform' environment variable to avoid unwanted collision in InstallDotNetCore.targets file # some computer has this env var defined (e.g. Some HP) if($env:Platform) { $env:Platform="" } function Print-Usage() { Write-Host "Common settings:" Write-Host " -configuration <value> Build configuration: 'Debug' or 'Release' (short: -c)" Write-Host " -platform <value> Platform configuration: 'x86', 'x64' or any valid Platform value to pass to msbuild" Write-Host " -verbosity <value> Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic] (short: -v)" Write-Host " -binaryLog Output binary log (short: -bl)" Write-Host " -help Print help and exit" Write-Host "" Write-Host "Actions:" Write-Host " -restore Restore dependencies (short: -r)" Write-Host " -build Build solution (short: -b)" Write-Host " -rebuild Rebuild solution" Write-Host " -deploy Deploy built VSIXes" Write-Host " -deployDeps Deploy dependencies (e.g. VSIXes for integration tests)" Write-Host " -test Run all unit tests in the solution (short: -t)" Write-Host " -integrationTest Run all integration tests in the solution" Write-Host " -performanceTest Run all performance tests in the solution" Write-Host " -pack Package build outputs into NuGet packages and Willow components" Write-Host " -sign Sign build outputs" Write-Host " -publish Publish artifacts (e.g. symbols)" Write-Host " -clean Clean the solution" Write-Host "" Write-Host "Advanced settings:" Write-Host " -projects <value> Semi-colon delimited list of sln/proj's to build. Globbing is supported (*.sln)" Write-Host " -ci Set when running on CI server" Write-Host " -excludeCIBinarylog Don't output binary log (short: -nobl)" Write-Host " -prepareMachine Prepare machine for CI run, clean up processes after build" Write-Host " -warnAsError <value> Sets warnaserror msbuild parameter ('true' or 'false')" Write-Host " -msbuildEngine <value> Msbuild engine to use to run build ('dotnet', 'vs', or unspecified)." Write-Host " -excludePrereleaseVS Set to exclude build engines in prerelease versions of Visual Studio" Write-Host "" Write-Host "Command line arguments not listed above are passed thru to msbuild." Write-Host "The above arguments can be shortened as much as to be unambiguous (e.g. -co for configuration, -t for test, etc.)." } . $PSScriptRoot\tools.ps1 function InitializeCustomToolset { if (-not $restore) { return } $script = Join-Path $EngRoot 'restore-toolset.ps1' if (Test-Path $script) { . $script } } function Build { $toolsetBuildProj = InitializeToolset InitializeCustomToolset $bl = if ($binaryLog) { '/bl:' + (Join-Path $LogDir 'Build.binlog') } else { '' } $platformArg = if ($platform) { "/p:Platform=$platform" } else { '' } if ($projects) { # Re-assign properties to a new variable because PowerShell doesn't let us append properties directly for unclear reasons. # Explicitly set the type as string[] because otherwise PowerShell would make this char[] if $properties is empty. [string[]] $msbuildArgs = $properties # Resolve relative project paths into full paths $projects = ($projects.Split(';').ForEach({Resolve-Path $_}) -join ';') $msbuildArgs += "/p:Projects=$projects" $properties = $msbuildArgs } MSBuild $toolsetBuildProj ` $bl ` $platformArg ` /p:Configuration=$configuration ` /p:RepoRoot=$RepoRoot ` /p:Restore=$restore ` /p:DeployDeps=$deployDeps ` /p:Build=$build ` /p:Rebuild=$rebuild ` /p:Deploy=$deploy ` /p:Test=$test ` /p:Pack=$pack ` /p:IntegrationTest=$integrationTest ` /p:PerformanceTest=$performanceTest ` /p:Sign=$sign ` /p:Publish=$publish ` @properties } try { if ($clean) { if (Test-Path $ArtifactsDir) { Remove-Item -Recurse -Force $ArtifactsDir Write-Host 'Artifacts directory deleted.' } exit 0 } if ($help -or (($null -ne $properties) -and ($properties.Contains('/help') -or $properties.Contains('/?')))) { Print-Usage exit 0 } if ($ci) { if (-not $excludeCIBinarylog) { $binaryLog = $true } $nodeReuse = $false } if ($restore) { InitializeNativeTools } Build } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_ ExitWithExitCode 1 } ExitWithExitCode 0
[CmdletBinding(PositionalBinding=$false)] Param( [string][Alias('c')]$configuration = "Debug", [string]$platform = $null, [string] $projects, [string][Alias('v')]$verbosity = "minimal", [string] $msbuildEngine = $null, [bool] $warnAsError = $true, [bool] $nodeReuse = $true, [switch][Alias('r')]$restore, [switch] $deployDeps, [switch][Alias('b')]$build, [switch] $rebuild, [switch] $deploy, [switch][Alias('t')]$test, [switch] $integrationTest, [switch] $performanceTest, [switch] $sign, [switch] $pack, [switch] $publish, [switch] $clean, [switch][Alias('bl')]$binaryLog, [switch][Alias('nobl')]$excludeCIBinarylog, [switch] $ci, [switch] $prepareMachine, [string] $runtimeSourceFeed = '', [string] $runtimeSourceFeedKey = '', [switch] $excludePrereleaseVS, [switch] $help, [Parameter(ValueFromRemainingArguments=$true)][String[]]$properties ) # Unset 'Platform' environment variable to avoid unwanted collision in InstallDotNetCore.targets file # some computer has this env var defined (e.g. Some HP) if($env:Platform) { $env:Platform="" } function Print-Usage() { Write-Host "Common settings:" Write-Host " -configuration <value> Build configuration: 'Debug' or 'Release' (short: -c)" Write-Host " -platform <value> Platform configuration: 'x86', 'x64' or any valid Platform value to pass to msbuild" Write-Host " -verbosity <value> Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic] (short: -v)" Write-Host " -binaryLog Output binary log (short: -bl)" Write-Host " -help Print help and exit" Write-Host "" Write-Host "Actions:" Write-Host " -restore Restore dependencies (short: -r)" Write-Host " -build Build solution (short: -b)" Write-Host " -rebuild Rebuild solution" Write-Host " -deploy Deploy built VSIXes" Write-Host " -deployDeps Deploy dependencies (e.g. VSIXes for integration tests)" Write-Host " -test Run all unit tests in the solution (short: -t)" Write-Host " -integrationTest Run all integration tests in the solution" Write-Host " -performanceTest Run all performance tests in the solution" Write-Host " -pack Package build outputs into NuGet packages and Willow components" Write-Host " -sign Sign build outputs" Write-Host " -publish Publish artifacts (e.g. symbols)" Write-Host " -clean Clean the solution" Write-Host "" Write-Host "Advanced settings:" Write-Host " -projects <value> Semi-colon delimited list of sln/proj's to build. Globbing is supported (*.sln)" Write-Host " -ci Set when running on CI server" Write-Host " -excludeCIBinarylog Don't output binary log (short: -nobl)" Write-Host " -prepareMachine Prepare machine for CI run, clean up processes after build" Write-Host " -warnAsError <value> Sets warnaserror msbuild parameter ('true' or 'false')" Write-Host " -msbuildEngine <value> Msbuild engine to use to run build ('dotnet', 'vs', or unspecified)." Write-Host " -excludePrereleaseVS Set to exclude build engines in prerelease versions of Visual Studio" Write-Host "" Write-Host "Command line arguments not listed above are passed thru to msbuild." Write-Host "The above arguments can be shortened as much as to be unambiguous (e.g. -co for configuration, -t for test, etc.)." } . $PSScriptRoot\tools.ps1 function InitializeCustomToolset { if (-not $restore) { return } $script = Join-Path $EngRoot 'restore-toolset.ps1' if (Test-Path $script) { . $script } } function Build { $toolsetBuildProj = InitializeToolset InitializeCustomToolset $bl = if ($binaryLog) { '/bl:' + (Join-Path $LogDir 'Build.binlog') } else { '' } $platformArg = if ($platform) { "/p:Platform=$platform" } else { '' } if ($projects) { # Re-assign properties to a new variable because PowerShell doesn't let us append properties directly for unclear reasons. # Explicitly set the type as string[] because otherwise PowerShell would make this char[] if $properties is empty. [string[]] $msbuildArgs = $properties # Resolve relative project paths into full paths $projects = ($projects.Split(';').ForEach({Resolve-Path $_}) -join ';') $msbuildArgs += "/p:Projects=$projects" $properties = $msbuildArgs } MSBuild $toolsetBuildProj ` $bl ` $platformArg ` /p:Configuration=$configuration ` /p:RepoRoot=$RepoRoot ` /p:Restore=$restore ` /p:DeployDeps=$deployDeps ` /p:Build=$build ` /p:Rebuild=$rebuild ` /p:Deploy=$deploy ` /p:Test=$test ` /p:Pack=$pack ` /p:IntegrationTest=$integrationTest ` /p:PerformanceTest=$performanceTest ` /p:Sign=$sign ` /p:Publish=$publish ` @properties } try { if ($clean) { if (Test-Path $ArtifactsDir) { Remove-Item -Recurse -Force $ArtifactsDir Write-Host 'Artifacts directory deleted.' } exit 0 } if ($help -or (($null -ne $properties) -and ($properties.Contains('/help') -or $properties.Contains('/?')))) { Print-Usage exit 0 } if ($ci) { if (-not $excludeCIBinarylog) { $binaryLog = $true } $nodeReuse = $false } if ($restore) { InitializeNativeTools } Build } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_ ExitWithExitCode 1 } ExitWithExitCode 0
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/build-utils.ps1
# Collection of powershell build utility functions that we use across our scripts. Set-StrictMode -version 2.0 $ErrorActionPreference="Stop" # Import Arcade functions . (Join-Path $PSScriptRoot "common\tools.ps1") $VSSetupDir = Join-Path $ArtifactsDir "VSSetup\$configuration" $PackagesDir = Join-Path $ArtifactsDir "packages\$configuration" $PublishDataUrl = "https://raw.githubusercontent.com/dotnet/roslyn/main/eng/config/PublishData.json" $binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $false } $nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { $false } $bootstrapDir = if (Test-Path variable:bootstrapDir) { $bootstrapDir } else { "" } $bootstrapConfiguration = if (Test-Path variable:bootstrapConfiguration) { $bootstrapConfiguration } else { "Release" } $properties = if (Test-Path variable:properties) { $properties } else { @() } function GetProjectOutputBinary([string]$fileName, [string]$projectName = "", [string]$configuration = $script:configuration, [string]$tfm = "net472", [string]$rid = "", [bool]$published = $false) { $projectName = if ($projectName -ne "") { $projectName } else { [System.IO.Path]::GetFileNameWithoutExtension($fileName) } $publishDir = if ($published) { "publish\" } else { "" } $ridDir = if ($rid -ne "") { "$rid\" } else { "" } return Join-Path $ArtifactsDir "bin\$projectName\$configuration\$tfm\$ridDir$publishDir$fileName" } function GetPublishData() { if (Test-Path variable:global:_PublishData) { return $global:_PublishData } Write-Host "Downloading $PublishDataUrl" $content = (Invoke-WebRequest -Uri $PublishDataUrl -UseBasicParsing).Content return $global:_PublishData = ConvertFrom-Json $content } function GetBranchPublishData([string]$branchName) { $data = GetPublishData if (Get-Member -InputObject $data.branches -Name $branchName) { return $data.branches.$branchName } else { return $null } } function GetFeedPublishData() { $data = GetPublishData return $data.feeds } function GetPackagesPublishData([string]$packageFeeds) { $data = GetPublishData if (Get-Member -InputObject $data.packages -Name $packageFeeds) { return $data.packages.$packageFeeds } else { return $null } } function GetReleasePublishData([string]$releaseName) { $data = GetPublishData if (Get-Member -InputObject $data.releases -Name $releaseName) { return $data.releases.$releaseName } else { return $null } } # Handy function for executing a command in powershell and throwing if it # fails. # # Use this when the full command is known at script authoring time and # doesn't require any dynamic argument build up. Example: # # Exec-Block { & $msbuild Test.proj } # # Original sample came from: http://jameskovacs.com/2010/02/25/the-exec-problem/ function Exec-Block([scriptblock]$cmd) { & $cmd # Need to check both of these cases for errors as they represent different items # - $?: did the powershell script block throw an error # - $lastexitcode: did a windows command executed by the script block end in error if ((-not $?) -or ($lastexitcode -ne 0)) { throw "Command failed to execute: $cmd" } } function Exec-CommandCore([string]$command, [string]$commandArgs, [switch]$useConsole = $true) { if ($useConsole) { $exitCode = Exec-Process $command $commandArgs if ($exitCode -ne 0) { throw "Command failed to execute with exit code $($exitCode): $command $commandArgs" } return } $startInfo = New-Object System.Diagnostics.ProcessStartInfo $startInfo.FileName = $command $startInfo.Arguments = $commandArgs $startInfo.UseShellExecute = $false $startInfo.WorkingDirectory = Get-Location $startInfo.RedirectStandardOutput = $true $startInfo.CreateNoWindow = $true $process = New-Object System.Diagnostics.Process $process.StartInfo = $startInfo $process.Start() | Out-Null $finished = $false try { # The OutputDataReceived event doesn't fire as events are sent by the # process in powershell. Possibly due to subtlties of how Powershell # manages the thread pool that I'm not aware of. Using blocking # reading here as an alternative which is fine since this blocks # on completion already. $out = $process.StandardOutput while (-not $out.EndOfStream) { $line = $out.ReadLine() Write-Output $line } while (-not $process.WaitForExit(100)) { # Non-blocking loop done to allow ctr-c interrupts } $finished = $true if ($process.ExitCode -ne 0) { throw "Command failed to execute with exit code $($process.ExitCode): $command $commandArgs" } } finally { # If we didn't finish then an error occurred or the user hit ctrl-c. Either # way kill the process if (-not $finished) { $process.Kill() } } } # Handy function for executing a windows command which needs to go through # windows command line parsing. # # Use this when the command arguments are stored in a variable. Particularly # when the variable needs reparsing by the windows command line. Example: # # $args = "/p:ManualBuild=true Test.proj" # Exec-Command $msbuild $args # function Exec-Command([string]$command, [string]$commandArgs) { Exec-CommandCore -command $command -commandArgs $commandargs -useConsole:$false } # Functions exactly like Exec-Command but lets the process re-use the current # console. This means items like colored output will function correctly. # # In general this command should be used in place of # Exec-Command $msbuild $args | Out-Host # function Exec-Console([string]$command, [string]$commandArgs) { Exec-CommandCore -command $command -commandArgs $commandargs -useConsole:$true } # Handy function for executing a powershell script in a clean environment with # arguments. Prefer this over & sourcing a script as it will both use a clean # environment and do proper error checking function Exec-Script([string]$script, [string]$scriptArgs = "") { Exec-Command "powershell" "-noprofile -executionPolicy RemoteSigned -file `"$script`" $scriptArgs" } # Ensure the proper .NET Core SDK is available. Returns the location to the dotnet.exe. function Ensure-DotnetSdk() { $dotnetInstallDir = (InitializeDotNetCli -install:$true) $dotnetTestPath = Join-Path $dotnetInstallDir "dotnet.exe" if (Test-Path -Path $dotnetTestPath) { return $dotnetTestPath } $dotnetTestPath = Join-Path $dotnetInstallDir "dotnet" if (Test-Path -Path $dotnetTestPath) { return $dotnetTestPath } throw "Could not find dotnet executable in $dotnetInstallDir" } # Walks up the source tree, starting at the given file's directory, and returns a FileInfo object for the first .csproj file it finds, if any. function Get-ProjectFile([object]$fileInfo) { Push-Location Set-Location $fileInfo.Directory try { while ($true) { # search up from the current file for a folder containing a project file $files = Get-ChildItem *.csproj,*.vbproj if ($files) { return $files[0] } else { $location = Get-Location Set-Location .. if ((Get-Location).Path -eq $location.Path) { # our location didn't change. We must be at the drive root, so give up return $null } } } } finally { Pop-Location } } function Get-VersionCore([string]$name, [string]$versionFile) { $name = $name.Replace(".", "") $name = $name.Replace("-", "") $nodeName = "$($name)Version" $x = [xml](Get-Content -raw $versionFile) $node = $x.SelectSingleNode("//Project/PropertyGroup/$nodeName") if ($node -ne $null) { return $node.InnerText } throw "Cannot find package $name in $versionFile" } # Return the version of the NuGet package as used in this repo function Get-PackageVersion([string]$name) { return Get-VersionCore $name (Join-Path $EngRoot "Versions.props") } # Locate the directory where our NuGet packages will be deployed. Needs to be kept in sync # with the logic in Version.props function Get-PackagesDir() { $d = $null if ($env:NUGET_PACKAGES -ne $null) { $d = $env:NUGET_PACKAGES } else { $d = Join-Path $env:UserProfile ".nuget\packages\" } Create-Directory $d return $d } # Locate the directory of a specific NuGet package which is restored via our main # toolset values. function Get-PackageDir([string]$name, [string]$version = "") { if ($version -eq "") { $version = Get-PackageVersion $name } $p = Get-PackagesDir $p = Join-Path $p $name.ToLowerInvariant() $p = Join-Path $p $version return $p } function Run-MSBuild([string]$projectFilePath, [string]$buildArgs = "", [string]$logFileName = "", [switch]$parallel = $true, [switch]$summary = $true, [switch]$warnAsError = $true, [string]$configuration = $script:configuration, [switch]$runAnalyzers = $false) { # Because we override the C#/VB toolset to build against our LKG package, it is important # that we do not reuse MSBuild nodes from other jobs/builds on the machine. Otherwise, # we'll run into issues such as https://github.com/dotnet/roslyn/issues/6211. # MSBuildAdditionalCommandLineArgs= $args = "/p:TreatWarningsAsErrors=true /nologo /nodeReuse:false /p:Configuration=$configuration "; if ($warnAsError) { $args += " /warnaserror" } if ($summary) { $args += " /consoleloggerparameters:Verbosity=minimal;summary" } else { $args += " /consoleloggerparameters:Verbosity=minimal" } if ($parallel) { $args += " /m" } if ($runAnalyzers) { $args += " /p:RunAnalyzersDuringBuild=true" } if ($binaryLog) { if ($logFileName -eq "") { $logFileName = [IO.Path]::GetFileNameWithoutExtension($projectFilePath) } $logFileName = [IO.Path]::ChangeExtension($logFileName, ".binlog") $logFilePath = Join-Path $LogDir $logFileName $args += " /bl:$logFilePath" } if ($officialBuildId) { $args += " /p:OfficialBuildId=" + $officialBuildId } if ($ci) { $args += " /p:ContinuousIntegrationBuild=true" } if ($bootstrapDir -ne "") { $args += " /p:BootstrapBuildPath=$bootstrapDir" } $args += " $buildArgs" $args += " $projectFilePath" $args += " $properties" $buildTool = InitializeBuildTool Exec-Console $buildTool.Path "$($buildTool.Command) $args" } # Create a bootstrap build of the compiler. Returns the directory where the bootstrap build # is located. # # Important to not set $script:bootstrapDir here yet as we're actually in the process of # building the bootstrap. function Make-BootstrapBuild([switch]$force32 = $false) { Write-Host "Building bootstrap compiler" $dir = Join-Path $ArtifactsDir "Bootstrap" Remove-Item -re $dir -ErrorAction SilentlyContinue Create-Directory $dir $packageName = "Microsoft.Net.Compilers.Toolset" $projectPath = "src\NuGet\$packageName\$packageName.Package.csproj" $force32Flag = if ($force32) { " /p:BOOTSTRAP32=true" } else { "" } Run-MSBuild $projectPath "/restore /t:Pack /p:RoslynEnforceCodeStyle=false /p:RunAnalyzersDuringBuild=false /p:DotNetUseShippingVersions=true /p:InitialDefineConstants=BOOTSTRAP /p:PackageOutputPath=`"$dir`" /p:EnableNgenOptimization=false /p:PublishWindowsPdb=false $force32Flag" -logFileName "Bootstrap" -configuration $bootstrapConfiguration -runAnalyzers $packageFile = Get-ChildItem -Path $dir -Filter "$packageName.*.nupkg" Unzip (Join-Path $dir $packageFile.Name) $dir Write-Host "Cleaning Bootstrap compiler artifacts" Run-MSBuild $projectPath "/t:Clean" -logFileName "BootstrapClean" return $dir }
# Collection of powershell build utility functions that we use across our scripts. Set-StrictMode -version 2.0 $ErrorActionPreference="Stop" # Import Arcade functions . (Join-Path $PSScriptRoot "common\tools.ps1") $VSSetupDir = Join-Path $ArtifactsDir "VSSetup\$configuration" $PackagesDir = Join-Path $ArtifactsDir "packages\$configuration" $PublishDataUrl = "https://raw.githubusercontent.com/dotnet/roslyn/main/eng/config/PublishData.json" $binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $false } $nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { $false } $bootstrapDir = if (Test-Path variable:bootstrapDir) { $bootstrapDir } else { "" } $bootstrapConfiguration = if (Test-Path variable:bootstrapConfiguration) { $bootstrapConfiguration } else { "Release" } $properties = if (Test-Path variable:properties) { $properties } else { @() } function GetProjectOutputBinary([string]$fileName, [string]$projectName = "", [string]$configuration = $script:configuration, [string]$tfm = "net472", [string]$rid = "", [bool]$published = $false) { $projectName = if ($projectName -ne "") { $projectName } else { [System.IO.Path]::GetFileNameWithoutExtension($fileName) } $publishDir = if ($published) { "publish\" } else { "" } $ridDir = if ($rid -ne "") { "$rid\" } else { "" } return Join-Path $ArtifactsDir "bin\$projectName\$configuration\$tfm\$ridDir$publishDir$fileName" } function GetPublishData() { if (Test-Path variable:global:_PublishData) { return $global:_PublishData } Write-Host "Downloading $PublishDataUrl" $content = (Invoke-WebRequest -Uri $PublishDataUrl -UseBasicParsing).Content return $global:_PublishData = ConvertFrom-Json $content } function GetBranchPublishData([string]$branchName) { $data = GetPublishData if (Get-Member -InputObject $data.branches -Name $branchName) { return $data.branches.$branchName } else { return $null } } function GetFeedPublishData() { $data = GetPublishData return $data.feeds } function GetPackagesPublishData([string]$packageFeeds) { $data = GetPublishData if (Get-Member -InputObject $data.packages -Name $packageFeeds) { return $data.packages.$packageFeeds } else { return $null } } function GetReleasePublishData([string]$releaseName) { $data = GetPublishData if (Get-Member -InputObject $data.releases -Name $releaseName) { return $data.releases.$releaseName } else { return $null } } # Handy function for executing a command in powershell and throwing if it # fails. # # Use this when the full command is known at script authoring time and # doesn't require any dynamic argument build up. Example: # # Exec-Block { & $msbuild Test.proj } # # Original sample came from: http://jameskovacs.com/2010/02/25/the-exec-problem/ function Exec-Block([scriptblock]$cmd) { & $cmd # Need to check both of these cases for errors as they represent different items # - $?: did the powershell script block throw an error # - $lastexitcode: did a windows command executed by the script block end in error if ((-not $?) -or ($lastexitcode -ne 0)) { throw "Command failed to execute: $cmd" } } function Exec-CommandCore([string]$command, [string]$commandArgs, [switch]$useConsole = $true) { if ($useConsole) { $exitCode = Exec-Process $command $commandArgs if ($exitCode -ne 0) { throw "Command failed to execute with exit code $($exitCode): $command $commandArgs" } return } $startInfo = New-Object System.Diagnostics.ProcessStartInfo $startInfo.FileName = $command $startInfo.Arguments = $commandArgs $startInfo.UseShellExecute = $false $startInfo.WorkingDirectory = Get-Location $startInfo.RedirectStandardOutput = $true $startInfo.CreateNoWindow = $true $process = New-Object System.Diagnostics.Process $process.StartInfo = $startInfo $process.Start() | Out-Null $finished = $false try { # The OutputDataReceived event doesn't fire as events are sent by the # process in powershell. Possibly due to subtlties of how Powershell # manages the thread pool that I'm not aware of. Using blocking # reading here as an alternative which is fine since this blocks # on completion already. $out = $process.StandardOutput while (-not $out.EndOfStream) { $line = $out.ReadLine() Write-Output $line } while (-not $process.WaitForExit(100)) { # Non-blocking loop done to allow ctr-c interrupts } $finished = $true if ($process.ExitCode -ne 0) { throw "Command failed to execute with exit code $($process.ExitCode): $command $commandArgs" } } finally { # If we didn't finish then an error occurred or the user hit ctrl-c. Either # way kill the process if (-not $finished) { $process.Kill() } } } # Handy function for executing a windows command which needs to go through # windows command line parsing. # # Use this when the command arguments are stored in a variable. Particularly # when the variable needs reparsing by the windows command line. Example: # # $args = "/p:ManualBuild=true Test.proj" # Exec-Command $msbuild $args # function Exec-Command([string]$command, [string]$commandArgs) { Exec-CommandCore -command $command -commandArgs $commandargs -useConsole:$false } # Functions exactly like Exec-Command but lets the process re-use the current # console. This means items like colored output will function correctly. # # In general this command should be used in place of # Exec-Command $msbuild $args | Out-Host # function Exec-Console([string]$command, [string]$commandArgs) { Exec-CommandCore -command $command -commandArgs $commandargs -useConsole:$true } # Handy function for executing a powershell script in a clean environment with # arguments. Prefer this over & sourcing a script as it will both use a clean # environment and do proper error checking function Exec-Script([string]$script, [string]$scriptArgs = "") { Exec-Command "powershell" "-noprofile -executionPolicy RemoteSigned -file `"$script`" $scriptArgs" } # Ensure the proper .NET Core SDK is available. Returns the location to the dotnet.exe. function Ensure-DotnetSdk() { $dotnetInstallDir = (InitializeDotNetCli -install:$true) $dotnetTestPath = Join-Path $dotnetInstallDir "dotnet.exe" if (Test-Path -Path $dotnetTestPath) { return $dotnetTestPath } $dotnetTestPath = Join-Path $dotnetInstallDir "dotnet" if (Test-Path -Path $dotnetTestPath) { return $dotnetTestPath } throw "Could not find dotnet executable in $dotnetInstallDir" } # Walks up the source tree, starting at the given file's directory, and returns a FileInfo object for the first .csproj file it finds, if any. function Get-ProjectFile([object]$fileInfo) { Push-Location Set-Location $fileInfo.Directory try { while ($true) { # search up from the current file for a folder containing a project file $files = Get-ChildItem *.csproj,*.vbproj if ($files) { return $files[0] } else { $location = Get-Location Set-Location .. if ((Get-Location).Path -eq $location.Path) { # our location didn't change. We must be at the drive root, so give up return $null } } } } finally { Pop-Location } } function Get-VersionCore([string]$name, [string]$versionFile) { $name = $name.Replace(".", "") $name = $name.Replace("-", "") $nodeName = "$($name)Version" $x = [xml](Get-Content -raw $versionFile) $node = $x.SelectSingleNode("//Project/PropertyGroup/$nodeName") if ($node -ne $null) { return $node.InnerText } throw "Cannot find package $name in $versionFile" } # Return the version of the NuGet package as used in this repo function Get-PackageVersion([string]$name) { return Get-VersionCore $name (Join-Path $EngRoot "Versions.props") } # Locate the directory where our NuGet packages will be deployed. Needs to be kept in sync # with the logic in Version.props function Get-PackagesDir() { $d = $null if ($env:NUGET_PACKAGES -ne $null) { $d = $env:NUGET_PACKAGES } else { $d = Join-Path $env:UserProfile ".nuget\packages\" } Create-Directory $d return $d } # Locate the directory of a specific NuGet package which is restored via our main # toolset values. function Get-PackageDir([string]$name, [string]$version = "") { if ($version -eq "") { $version = Get-PackageVersion $name } $p = Get-PackagesDir $p = Join-Path $p $name.ToLowerInvariant() $p = Join-Path $p $version return $p } function Run-MSBuild([string]$projectFilePath, [string]$buildArgs = "", [string]$logFileName = "", [switch]$parallel = $true, [switch]$summary = $true, [switch]$warnAsError = $true, [string]$configuration = $script:configuration, [switch]$runAnalyzers = $false) { # Because we override the C#/VB toolset to build against our LKG package, it is important # that we do not reuse MSBuild nodes from other jobs/builds on the machine. Otherwise, # we'll run into issues such as https://github.com/dotnet/roslyn/issues/6211. # MSBuildAdditionalCommandLineArgs= $args = "/p:TreatWarningsAsErrors=true /nologo /nodeReuse:false /p:Configuration=$configuration "; if ($warnAsError) { $args += " /warnaserror" } if ($summary) { $args += " /consoleloggerparameters:Verbosity=minimal;summary" } else { $args += " /consoleloggerparameters:Verbosity=minimal" } if ($parallel) { $args += " /m" } if ($runAnalyzers) { $args += " /p:RunAnalyzersDuringBuild=true" } if ($binaryLog) { if ($logFileName -eq "") { $logFileName = [IO.Path]::GetFileNameWithoutExtension($projectFilePath) } $logFileName = [IO.Path]::ChangeExtension($logFileName, ".binlog") $logFilePath = Join-Path $LogDir $logFileName $args += " /bl:$logFilePath" } if ($officialBuildId) { $args += " /p:OfficialBuildId=" + $officialBuildId } if ($ci) { $args += " /p:ContinuousIntegrationBuild=true" } if ($bootstrapDir -ne "") { $args += " /p:BootstrapBuildPath=$bootstrapDir" } $args += " $buildArgs" $args += " $projectFilePath" $args += " $properties" $buildTool = InitializeBuildTool Exec-Console $buildTool.Path "$($buildTool.Command) $args" } # Create a bootstrap build of the compiler. Returns the directory where the bootstrap build # is located. # # Important to not set $script:bootstrapDir here yet as we're actually in the process of # building the bootstrap. function Make-BootstrapBuild([switch]$force32 = $false) { Write-Host "Building bootstrap compiler" $dir = Join-Path $ArtifactsDir "Bootstrap" Remove-Item -re $dir -ErrorAction SilentlyContinue Create-Directory $dir $packageName = "Microsoft.Net.Compilers.Toolset" $projectPath = "src\NuGet\$packageName\$packageName.Package.csproj" $force32Flag = if ($force32) { " /p:BOOTSTRAP32=true" } else { "" } Run-MSBuild $projectPath "/restore /t:Pack /p:RoslynEnforceCodeStyle=false /p:RunAnalyzersDuringBuild=false /p:DotNetUseShippingVersions=true /p:InitialDefineConstants=BOOTSTRAP /p:PackageOutputPath=`"$dir`" /p:EnableNgenOptimization=false /p:PublishWindowsPdb=false $force32Flag" -logFileName "Bootstrap" -configuration $bootstrapConfiguration -runAnalyzers $packageFile = Get-ChildItem -Path $dir -Filter "$packageName.*.nupkg" Unzip (Join-Path $dir $packageFile.Name) $dir Write-Host "Cleaning Bootstrap compiler artifacts" Run-MSBuild $projectPath "/t:Clean" -logFileName "BootstrapClean" return $dir }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/pipeline-logging-functions.sh
#!/usr/bin/env bash function Write-PipelineTelemetryError { local telemetry_category='' local force=false local function_args=() local message='' while [[ $# -gt 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -category|-c) telemetry_category=$2 shift ;; -force|-f) force=true ;; -*) function_args+=("$1 $2") shift ;; *) message=$* ;; esac shift done if [[ $force != true ]] && [[ "$ci" != true ]]; then echo "$message" >&2 return fi if [[ $force == true ]]; then function_args+=("-force") fi message="(NETCORE_ENGINEERING_TELEMETRY=$telemetry_category) $message" function_args+=("$message") Write-PipelineTaskError ${function_args[@]} } function Write-PipelineTaskError { local message_type="error" local sourcepath='' local linenumber='' local columnnumber='' local error_code='' local force=false while [[ $# -gt 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -type|-t) message_type=$2 shift ;; -sourcepath|-s) sourcepath=$2 shift ;; -linenumber|-ln) linenumber=$2 shift ;; -columnnumber|-cn) columnnumber=$2 shift ;; -errcode|-e) error_code=$2 shift ;; -force|-f) force=true ;; *) break ;; esac shift done if [[ $force != true ]] && [[ "$ci" != true ]]; then echo "$@" >&2 return fi local message="##vso[task.logissue" message="$message type=$message_type" if [ -n "$sourcepath" ]; then message="$message;sourcepath=$sourcepath" fi if [ -n "$linenumber" ]; then message="$message;linenumber=$linenumber" fi if [ -n "$columnnumber" ]; then message="$message;columnnumber=$columnnumber" fi if [ -n "$error_code" ]; then message="$message;code=$error_code" fi message="$message]$*" echo "$message" } function Write-PipelineSetVariable { if [[ "$ci" != true ]]; then return fi local name='' local value='' local secret=false local as_output=false local is_multi_job_variable=true while [[ $# -gt 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -name|-n) name=$2 shift ;; -value|-v) value=$2 shift ;; -secret|-s) secret=true ;; -as_output|-a) as_output=true ;; -is_multi_job_variable|-i) is_multi_job_variable=$2 shift ;; esac shift done value=${value/;/%3B} value=${value/\\r/%0D} value=${value/\\n/%0A} value=${value/]/%5D} local message="##vso[task.setvariable variable=$name;isSecret=$secret;isOutput=$is_multi_job_variable]$value" if [[ "$as_output" == true ]]; then $message else echo "$message" fi } function Write-PipelinePrependPath { local prepend_path='' while [[ $# -gt 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -path|-p) prepend_path=$2 shift ;; esac shift done export PATH="$prepend_path:$PATH" if [[ "$ci" == true ]]; then echo "##vso[task.prependpath]$prepend_path" fi } function Write-PipelineSetResult { local result='' local message='' while [[ $# -gt 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -result|-r) result=$2 shift ;; -message|-m) message=$2 shift ;; esac shift done if [[ "$ci" == true ]]; then echo "##vso[task.complete result=$result;]$message" fi }
#!/usr/bin/env bash function Write-PipelineTelemetryError { local telemetry_category='' local force=false local function_args=() local message='' while [[ $# -gt 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -category|-c) telemetry_category=$2 shift ;; -force|-f) force=true ;; -*) function_args+=("$1 $2") shift ;; *) message=$* ;; esac shift done if [[ $force != true ]] && [[ "$ci" != true ]]; then echo "$message" >&2 return fi if [[ $force == true ]]; then function_args+=("-force") fi message="(NETCORE_ENGINEERING_TELEMETRY=$telemetry_category) $message" function_args+=("$message") Write-PipelineTaskError ${function_args[@]} } function Write-PipelineTaskError { local message_type="error" local sourcepath='' local linenumber='' local columnnumber='' local error_code='' local force=false while [[ $# -gt 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -type|-t) message_type=$2 shift ;; -sourcepath|-s) sourcepath=$2 shift ;; -linenumber|-ln) linenumber=$2 shift ;; -columnnumber|-cn) columnnumber=$2 shift ;; -errcode|-e) error_code=$2 shift ;; -force|-f) force=true ;; *) break ;; esac shift done if [[ $force != true ]] && [[ "$ci" != true ]]; then echo "$@" >&2 return fi local message="##vso[task.logissue" message="$message type=$message_type" if [ -n "$sourcepath" ]; then message="$message;sourcepath=$sourcepath" fi if [ -n "$linenumber" ]; then message="$message;linenumber=$linenumber" fi if [ -n "$columnnumber" ]; then message="$message;columnnumber=$columnnumber" fi if [ -n "$error_code" ]; then message="$message;code=$error_code" fi message="$message]$*" echo "$message" } function Write-PipelineSetVariable { if [[ "$ci" != true ]]; then return fi local name='' local value='' local secret=false local as_output=false local is_multi_job_variable=true while [[ $# -gt 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -name|-n) name=$2 shift ;; -value|-v) value=$2 shift ;; -secret|-s) secret=true ;; -as_output|-a) as_output=true ;; -is_multi_job_variable|-i) is_multi_job_variable=$2 shift ;; esac shift done value=${value/;/%3B} value=${value/\\r/%0D} value=${value/\\n/%0A} value=${value/]/%5D} local message="##vso[task.setvariable variable=$name;isSecret=$secret;isOutput=$is_multi_job_variable]$value" if [[ "$as_output" == true ]]; then $message else echo "$message" fi } function Write-PipelinePrependPath { local prepend_path='' while [[ $# -gt 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -path|-p) prepend_path=$2 shift ;; esac shift done export PATH="$prepend_path:$PATH" if [[ "$ci" == true ]]; then echo "##vso[task.prependpath]$prepend_path" fi } function Write-PipelineSetResult { local result='' local message='' while [[ $# -gt 0 ]]; do opt="$(echo "${1/#--/-}" | tr "[:upper:]" "[:lower:]")" case "$opt" in -result|-r) result=$2 shift ;; -message|-m) message=$2 shift ;; esac shift done if [[ "$ci" == true ]]; then echo "##vso[task.complete result=$result;]$message" fi }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/post-build/post-build-utils.ps1
# Most of the functions in this file require the variables `MaestroApiEndPoint`, # `MaestroApiVersion` and `MaestroApiAccessToken` to be globally available. $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 # `tools.ps1` checks $ci to perform some actions. Since the post-build # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true $disableConfigureToolsetImport = $true . $PSScriptRoot\..\tools.ps1 function Create-MaestroApiRequestHeaders([string]$ContentType = 'application/json') { Validate-MaestroVars $headers = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' $headers.Add('Accept', $ContentType) $headers.Add('Authorization',"Bearer $MaestroApiAccessToken") return $headers } function Get-MaestroChannel([int]$ChannelId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders $apiEndpoint = "$MaestroApiEndPoint/api/channels/${ChannelId}?api-version=$MaestroApiVersion" $result = try { Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } return $result } function Get-MaestroBuild([int]$BuildId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/builds/${BuildId}?api-version=$MaestroApiVersion" $result = try { return Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } return $result } function Get-MaestroSubscriptions([string]$SourceRepository, [int]$ChannelId) { Validate-MaestroVars $SourceRepository = [System.Web.HttpUtility]::UrlEncode($SourceRepository) $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/subscriptions?sourceRepository=$SourceRepository&channelId=$ChannelId&api-version=$MaestroApiVersion" $result = try { Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } return $result } function Assign-BuildToChannel([int]$BuildId, [int]$ChannelId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/channels/${ChannelId}/builds/${BuildId}?api-version=$MaestroApiVersion" Invoke-WebRequest -Method Post -Uri $apiEndpoint -Headers $apiHeaders | Out-Null } function Trigger-Subscription([string]$SubscriptionId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/subscriptions/$SubscriptionId/trigger?api-version=$MaestroApiVersion" Invoke-WebRequest -Uri $apiEndpoint -Headers $apiHeaders -Method Post | Out-Null } function Validate-MaestroVars { try { Get-Variable MaestroApiEndPoint | Out-Null Get-Variable MaestroApiVersion | Out-Null Get-Variable MaestroApiAccessToken | Out-Null if (!($MaestroApiEndPoint -Match '^http[s]?://maestro-(int|prod).westus2.cloudapp.azure.com$')) { Write-PipelineTelemetryError -Category 'MaestroVars' -Message "MaestroApiEndPoint is not a valid Maestro URL. '$MaestroApiEndPoint'" ExitWithExitCode 1 } if (!($MaestroApiVersion -Match '^[0-9]{4}-[0-9]{2}-[0-9]{2}$')) { Write-PipelineTelemetryError -Category 'MaestroVars' -Message "MaestroApiVersion does not match a version string in the format yyyy-MM-DD. '$MaestroApiVersion'" ExitWithExitCode 1 } } catch { Write-PipelineTelemetryError -Category 'MaestroVars' -Message 'Error: Variables `MaestroApiEndPoint`, `MaestroApiVersion` and `MaestroApiAccessToken` are required while using this script.' Write-Host $_ ExitWithExitCode 1 } }
# Most of the functions in this file require the variables `MaestroApiEndPoint`, # `MaestroApiVersion` and `MaestroApiAccessToken` to be globally available. $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 # `tools.ps1` checks $ci to perform some actions. Since the post-build # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true $disableConfigureToolsetImport = $true . $PSScriptRoot\..\tools.ps1 function Create-MaestroApiRequestHeaders([string]$ContentType = 'application/json') { Validate-MaestroVars $headers = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' $headers.Add('Accept', $ContentType) $headers.Add('Authorization',"Bearer $MaestroApiAccessToken") return $headers } function Get-MaestroChannel([int]$ChannelId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders $apiEndpoint = "$MaestroApiEndPoint/api/channels/${ChannelId}?api-version=$MaestroApiVersion" $result = try { Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } return $result } function Get-MaestroBuild([int]$BuildId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/builds/${BuildId}?api-version=$MaestroApiVersion" $result = try { return Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } return $result } function Get-MaestroSubscriptions([string]$SourceRepository, [int]$ChannelId) { Validate-MaestroVars $SourceRepository = [System.Web.HttpUtility]::UrlEncode($SourceRepository) $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/subscriptions?sourceRepository=$SourceRepository&channelId=$ChannelId&api-version=$MaestroApiVersion" $result = try { Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } return $result } function Assign-BuildToChannel([int]$BuildId, [int]$ChannelId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/channels/${ChannelId}/builds/${BuildId}?api-version=$MaestroApiVersion" Invoke-WebRequest -Method Post -Uri $apiEndpoint -Headers $apiHeaders | Out-Null } function Trigger-Subscription([string]$SubscriptionId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/subscriptions/$SubscriptionId/trigger?api-version=$MaestroApiVersion" Invoke-WebRequest -Uri $apiEndpoint -Headers $apiHeaders -Method Post | Out-Null } function Validate-MaestroVars { try { Get-Variable MaestroApiEndPoint | Out-Null Get-Variable MaestroApiVersion | Out-Null Get-Variable MaestroApiAccessToken | Out-Null if (!($MaestroApiEndPoint -Match '^http[s]?://maestro-(int|prod).westus2.cloudapp.azure.com$')) { Write-PipelineTelemetryError -Category 'MaestroVars' -Message "MaestroApiEndPoint is not a valid Maestro URL. '$MaestroApiEndPoint'" ExitWithExitCode 1 } if (!($MaestroApiVersion -Match '^[0-9]{4}-[0-9]{2}-[0-9]{2}$')) { Write-PipelineTelemetryError -Category 'MaestroVars' -Message "MaestroApiVersion does not match a version string in the format yyyy-MM-DD. '$MaestroApiVersion'" ExitWithExitCode 1 } } catch { Write-PipelineTelemetryError -Category 'MaestroVars' -Message 'Error: Variables `MaestroApiEndPoint`, `MaestroApiVersion` and `MaestroApiAccessToken` are required while using this script.' Write-Host $_ ExitWithExitCode 1 } }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/VisualBasic/Test/Semantic/My Project/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/sdl/run-sdl.ps1
Param( [string] $GuardianCliLocation, [string] $WorkingDirectory, [string] $GdnFolder, [string] $UpdateBaseline, [string] $GuardianLoggerLevel='Standard' ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 $disableConfigureToolsetImport = $true $global:LASTEXITCODE = 0 try { # `tools.ps1` checks $ci to perform some actions. Since the SDL # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true . $PSScriptRoot\..\tools.ps1 # We store config files in the r directory of .gdn $gdnConfigPath = Join-Path $GdnFolder 'r' $ValidPath = Test-Path $GuardianCliLocation if ($ValidPath -eq $False) { Write-PipelineTelemetryError -Force -Category 'Sdl' -Message "Invalid Guardian CLI Location." ExitWithExitCode 1 } $gdnConfigFiles = Get-ChildItem $gdnConfigPath -Recurse -Include '*.gdnconfig' Write-Host "Discovered Guardian config files:" $gdnConfigFiles | Out-String | Write-Host Exec-BlockVerbosely { & $GuardianCliLocation run ` --working-directory $WorkingDirectory ` --baseline mainbaseline ` --update-baseline $UpdateBaseline ` --logger-level $GuardianLoggerLevel ` --config @gdnConfigFiles Exit-IfNZEC "Sdl" } } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 }
Param( [string] $GuardianCliLocation, [string] $WorkingDirectory, [string] $GdnFolder, [string] $UpdateBaseline, [string] $GuardianLoggerLevel='Standard' ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 $disableConfigureToolsetImport = $true $global:LASTEXITCODE = 0 try { # `tools.ps1` checks $ci to perform some actions. Since the SDL # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true . $PSScriptRoot\..\tools.ps1 # We store config files in the r directory of .gdn $gdnConfigPath = Join-Path $GdnFolder 'r' $ValidPath = Test-Path $GuardianCliLocation if ($ValidPath -eq $False) { Write-PipelineTelemetryError -Force -Category 'Sdl' -Message "Invalid Guardian CLI Location." ExitWithExitCode 1 } $gdnConfigFiles = Get-ChildItem $gdnConfigPath -Recurse -Include '*.gdnconfig' Write-Host "Discovered Guardian config files:" $gdnConfigFiles | Out-String | Write-Host Exec-BlockVerbosely { & $GuardianCliLocation run ` --working-directory $WorkingDirectory ` --baseline mainbaseline ` --update-baseline $UpdateBaseline ` --logger-level $GuardianLoggerLevel ` --config @gdnConfigFiles Exit-IfNZEC "Sdl" } } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/native/install-cmake.sh
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" . $scriptroot/common-library.sh base_uri= install_path= version= clean=false force=false download_retries=5 retry_wait_time_seconds=30 while (($# > 0)); do lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" case $lowerI in --baseuri) base_uri=$2 shift 2 ;; --installpath) install_path=$2 shift 2 ;; --version) version=$2 shift 2 ;; --clean) clean=true shift 1 ;; --force) force=true shift 1 ;; --downloadretries) download_retries=$2 shift 2 ;; --retrywaittimeseconds) retry_wait_time_seconds=$2 shift 2 ;; --help) echo "Common settings:" echo " --baseuri <value> Base file directory or Url wrom which to acquire tool archives" echo " --installpath <value> Base directory to install native tool to" echo " --clean Don't install the tool, just clean up the current install of the tool" echo " --force Force install of tools even if they previously exist" echo " --help Print help and exit" echo "" echo "Advanced settings:" echo " --downloadretries Total number of retry attempts" echo " --retrywaittimeseconds Wait time between retry attempts in seconds" echo "" exit 0 ;; esac done tool_name="cmake" tool_os=$(GetCurrentOS) tool_folder="$(echo $tool_os | tr "[:upper:]" "[:lower:]")" tool_arch="x86_64" tool_name_moniker="$tool_name-$version-$tool_os-$tool_arch" tool_install_directory="$install_path/$tool_name/$version" tool_file_path="$tool_install_directory/$tool_name_moniker/bin/$tool_name" shim_path="$install_path/$tool_name.sh" uri="${base_uri}/$tool_folder/$tool_name/$tool_name_moniker.tar.gz" # Clean up tool and installers if [[ $clean = true ]]; then echo "Cleaning $tool_install_directory" if [[ -d $tool_install_directory ]]; then rm -rf $tool_install_directory fi echo "Cleaning $shim_path" if [[ -f $shim_path ]]; then rm -rf $shim_path fi tool_temp_path=$(GetTempPathFileName $uri) echo "Cleaning $tool_temp_path" if [[ -f $tool_temp_path ]]; then rm -rf $tool_temp_path fi exit 0 fi # Install tool if [[ -f $tool_file_path ]] && [[ $force = false ]]; then echo "$tool_name ($version) already exists, skipping install" exit 0 fi DownloadAndExtract $uri $tool_install_directory $force $download_retries $retry_wait_time_seconds if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Installation failed' exit 1 fi # Generate Shim # Always rewrite shims so that we are referencing the expected version NewScriptShim $shim_path $tool_file_path true if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Shim generation failed' exit 1 fi exit 0
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" . $scriptroot/common-library.sh base_uri= install_path= version= clean=false force=false download_retries=5 retry_wait_time_seconds=30 while (($# > 0)); do lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" case $lowerI in --baseuri) base_uri=$2 shift 2 ;; --installpath) install_path=$2 shift 2 ;; --version) version=$2 shift 2 ;; --clean) clean=true shift 1 ;; --force) force=true shift 1 ;; --downloadretries) download_retries=$2 shift 2 ;; --retrywaittimeseconds) retry_wait_time_seconds=$2 shift 2 ;; --help) echo "Common settings:" echo " --baseuri <value> Base file directory or Url wrom which to acquire tool archives" echo " --installpath <value> Base directory to install native tool to" echo " --clean Don't install the tool, just clean up the current install of the tool" echo " --force Force install of tools even if they previously exist" echo " --help Print help and exit" echo "" echo "Advanced settings:" echo " --downloadretries Total number of retry attempts" echo " --retrywaittimeseconds Wait time between retry attempts in seconds" echo "" exit 0 ;; esac done tool_name="cmake" tool_os=$(GetCurrentOS) tool_folder="$(echo $tool_os | tr "[:upper:]" "[:lower:]")" tool_arch="x86_64" tool_name_moniker="$tool_name-$version-$tool_os-$tool_arch" tool_install_directory="$install_path/$tool_name/$version" tool_file_path="$tool_install_directory/$tool_name_moniker/bin/$tool_name" shim_path="$install_path/$tool_name.sh" uri="${base_uri}/$tool_folder/$tool_name/$tool_name_moniker.tar.gz" # Clean up tool and installers if [[ $clean = true ]]; then echo "Cleaning $tool_install_directory" if [[ -d $tool_install_directory ]]; then rm -rf $tool_install_directory fi echo "Cleaning $shim_path" if [[ -f $shim_path ]]; then rm -rf $shim_path fi tool_temp_path=$(GetTempPathFileName $uri) echo "Cleaning $tool_temp_path" if [[ -f $tool_temp_path ]]; then rm -rf $tool_temp_path fi exit 0 fi # Install tool if [[ -f $tool_file_path ]] && [[ $force = false ]]; then echo "$tool_name ($version) already exists, skipping install" exit 0 fi DownloadAndExtract $uri $tool_install_directory $force $download_retries $retry_wait_time_seconds if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Installation failed' exit 1 fi # Generate Shim # Always rewrite shims so that we are referencing the expected version NewScriptShim $shim_path $tool_file_path true if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Shim generation failed' exit 1 fi exit 0
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./test.sh
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" # resolve $SOURCE until the file is no longer a symlink while [[ -h $source ]]; do scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" source="$(readlink "$source")" # if $source was a relative symlink, we need to resolve it relative to the path where the # symlink file was located [[ $source != /* ]] && source="$scriptroot/$source" done scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" "$scriptroot/eng/build.sh" --test $@
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" # resolve $SOURCE until the file is no longer a symlink while [[ -h $source ]]; do scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" source="$(readlink "$source")" # if $source was a relative symlink, we need to resolve it relative to the path where the # symlink file was located [[ $source != /* ]] && source="$scriptroot/$source" done scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" "$scriptroot/eng/build.sh" --test $@
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/templates/job/onelocbuild.yml
parameters: # Optional: dependencies of the job dependsOn: '' # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool pool: vmImage: vs2017-win2016 CeapexPat: $(dn-bot-ceapex-package-r) # PAT for the loc AzDO instance https://dev.azure.com/ceapex GithubPat: $(BotAccount-dotnet-bot-repo-PAT) SourcesDirectory: $(Build.SourcesDirectory) CreatePr: true AutoCompletePr: false UseLfLineEndings: true UseCheckedInLocProjectJson: false LanguageSet: VS_Main_Languages LclSource: lclFilesInRepo LclPackageId: '' RepoType: gitHub GitHubOrg: dotnet MirrorRepo: '' MirrorBranch: main condition: '' jobs: - job: OneLocBuild dependsOn: ${{ parameters.dependsOn }} displayName: OneLocBuild pool: ${{ parameters.pool }} variables: - group: OneLocBuildVariables # Contains the CeapexPat and GithubPat - name: _GenerateLocProjectArguments value: -SourcesDirectory ${{ parameters.SourcesDirectory }} -LanguageSet "${{ parameters.LanguageSet }}" -CreateNeutralXlfs - ${{ if eq(parameters.UseCheckedInLocProjectJson, 'true') }}: - name: _GenerateLocProjectArguments value: ${{ variables._GenerateLocProjectArguments }} -UseCheckedInLocProjectJson steps: - task: Powershell@2 inputs: filePath: $(Build.SourcesDirectory)/eng/common/generate-locproject.ps1 arguments: $(_GenerateLocProjectArguments) displayName: Generate LocProject.json condition: ${{ parameters.condition }} - task: OneLocBuild@2 displayName: OneLocBuild env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) inputs: locProj: eng/Localize/LocProject.json outDir: $(Build.ArtifactStagingDirectory) lclSource: ${{ parameters.LclSource }} lclPackageId: ${{ parameters.LclPackageId }} isCreatePrSelected: ${{ parameters.CreatePr }} ${{ if eq(parameters.CreatePr, true) }}: isAutoCompletePrSelected: ${{ parameters.AutoCompletePr }} isUseLfLineEndingsSelected: ${{ parameters.UseLfLineEndings }} packageSourceAuth: patAuth patVariable: ${{ parameters.CeapexPat }} ${{ if eq(parameters.RepoType, 'gitHub') }}: repoType: ${{ parameters.RepoType }} gitHubPatVariable: "${{ parameters.GithubPat }}" ${{ if ne(parameters.MirrorRepo, '') }}: isMirrorRepoSelected: true gitHubOrganization: ${{ parameters.GitHubOrg }} mirrorRepo: ${{ parameters.MirrorRepo }} mirrorBranch: ${{ parameters.MirrorBranch }} condition: ${{ parameters.condition }} - task: PublishBuildArtifacts@1 displayName: Publish Localization Files inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/loc' PublishLocation: Container ArtifactName: Loc condition: ${{ parameters.condition }} - task: PublishBuildArtifacts@1 displayName: Publish LocProject.json inputs: PathtoPublish: '$(Build.SourcesDirectory)/eng/Localize/' PublishLocation: Container ArtifactName: Loc condition: ${{ parameters.condition }}
parameters: # Optional: dependencies of the job dependsOn: '' # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool pool: vmImage: vs2017-win2016 CeapexPat: $(dn-bot-ceapex-package-r) # PAT for the loc AzDO instance https://dev.azure.com/ceapex GithubPat: $(BotAccount-dotnet-bot-repo-PAT) SourcesDirectory: $(Build.SourcesDirectory) CreatePr: true AutoCompletePr: false UseLfLineEndings: true UseCheckedInLocProjectJson: false LanguageSet: VS_Main_Languages LclSource: lclFilesInRepo LclPackageId: '' RepoType: gitHub GitHubOrg: dotnet MirrorRepo: '' MirrorBranch: main condition: '' jobs: - job: OneLocBuild dependsOn: ${{ parameters.dependsOn }} displayName: OneLocBuild pool: ${{ parameters.pool }} variables: - group: OneLocBuildVariables # Contains the CeapexPat and GithubPat - name: _GenerateLocProjectArguments value: -SourcesDirectory ${{ parameters.SourcesDirectory }} -LanguageSet "${{ parameters.LanguageSet }}" -CreateNeutralXlfs - ${{ if eq(parameters.UseCheckedInLocProjectJson, 'true') }}: - name: _GenerateLocProjectArguments value: ${{ variables._GenerateLocProjectArguments }} -UseCheckedInLocProjectJson steps: - task: Powershell@2 inputs: filePath: $(Build.SourcesDirectory)/eng/common/generate-locproject.ps1 arguments: $(_GenerateLocProjectArguments) displayName: Generate LocProject.json condition: ${{ parameters.condition }} - task: OneLocBuild@2 displayName: OneLocBuild env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) inputs: locProj: eng/Localize/LocProject.json outDir: $(Build.ArtifactStagingDirectory) lclSource: ${{ parameters.LclSource }} lclPackageId: ${{ parameters.LclPackageId }} isCreatePrSelected: ${{ parameters.CreatePr }} ${{ if eq(parameters.CreatePr, true) }}: isAutoCompletePrSelected: ${{ parameters.AutoCompletePr }} isUseLfLineEndingsSelected: ${{ parameters.UseLfLineEndings }} packageSourceAuth: patAuth patVariable: ${{ parameters.CeapexPat }} ${{ if eq(parameters.RepoType, 'gitHub') }}: repoType: ${{ parameters.RepoType }} gitHubPatVariable: "${{ parameters.GithubPat }}" ${{ if ne(parameters.MirrorRepo, '') }}: isMirrorRepoSelected: true gitHubOrganization: ${{ parameters.GitHubOrg }} mirrorRepo: ${{ parameters.MirrorRepo }} mirrorBranch: ${{ parameters.MirrorBranch }} condition: ${{ parameters.condition }} - task: PublishBuildArtifacts@1 displayName: Publish Localization Files inputs: PathtoPublish: '$(Build.ArtifactStagingDirectory)/loc' PublishLocation: Container ArtifactName: Loc condition: ${{ parameters.condition }} - task: PublishBuildArtifacts@1 displayName: Publish LocProject.json inputs: PathtoPublish: '$(Build.SourcesDirectory)/eng/Localize/' PublishLocation: Container ArtifactName: Loc condition: ${{ parameters.condition }}
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/pipelines/checkout-windows-task.yml
# Shallow checkout sources on Windows steps: - checkout: none - script: | @echo on git init git remote add origin "$(Build.Repository.Uri)" git fetch --progress --no-tags --depth=1 origin "$(Build.SourceVersion)" git checkout "$(Build.SourceVersion)" displayName: Shallow Checkout
# Shallow checkout sources on Windows steps: - checkout: none - script: | @echo on git init git remote add origin "$(Build.Repository.Uri)" git fetch --progress --no-tags --depth=1 origin "$(Build.SourceVersion)" git checkout "$(Build.SourceVersion)" displayName: Shallow Checkout
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./scripts/edit-designers.ps1
# The new project system does not support designers. This blocks our ability to make XAML # changes through the designer. A rare event but necessary on occasiona. # # This script helps with the times where XAML changes are needed. It will temporarily revert # the projects which have XAML files to the legacy project system. The XAML edits can then # be processed and the coversion can be reverted. # # Bug tracking project system getting designer support # https://github.com/dotnet/project-system/issues/1467 [CmdletBinding(PositionalBinding=$false)] param () Set-StrictMode -version 2.0 $ErrorActionPreference = "Stop" $projectList = @( 'src\VisualStudio\Core\Impl\ServicesVisualStudioImpl.csproj', 'src\VisualStudio\CSharp\Impl\CSharpVisualStudio.csproj', 'src\VisualStudio\VisualBasic\Impl\BasicVisualStudio.vbproj', 'src\EditorFeatures\Core\EditorFeatures.csproj', 'src\VisualStudio\Core\Def\ServicesVisualStudio.csproj') # Edit all of the project files to no longer have a TargetFramework element. This is what # causes the selector to use the new project system. function Change-ProjectFiles() { foreach ($proj in $projectList) { $proj = Join-Path $RepoRoot $proj $lines = Get-Content $proj for ($i = 0; $i -lt $lines.Length; $i++) { $line = $lines[$i] if ($line -match ".*TargetFramework") { $lines[$i] = "<!-- DO NOT MERGE --> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion>" } } [IO.File]::WriteAllLines($proj, $lines) } } # Change the solution file to use the legacy project system GUID. function Change-Solution() { $solution = Join-Path $RepoRoot "Roslyn.sln" $lines = Get-Content $solution for ($i = 0; $i -lt $lines.Length; $i++) { $line = $lines[$i] foreach ($proj in $projectList) { if ($line -like "*$proj*") { Write-Host "Found $line" $ext = [IO.Path]::GetExtension($proj) if ($ext -eq ".csproj") { $oldGuid = "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC" $newGuid = "9A19103F-16F7-4668-BE54-9A1E7A4F7556" } else { $oldGuid = "F184B08F-C81C-45F6-A57F-5ABD9991F28F" $newGuid = "778DAE3C-4631-46EA-AA77-85C1314464D9" } $line = $line.Replace($newGuid, $oldGuid) Write-Host "New Line $line" $lines[$i] = $line } } } [IO.File]::WriteAllLines($solution, $lines) } try { . (Join-Path $PSScriptRoot "build-utils.ps1") Push-Location $RepoRoot Change-ProjectFiles Change-Solution exit 0 } catch { Write-Host $_ Write-Host $_.Exception Write-Host $_.ScriptStackTrace exit 1 } finally { Pop-Location }
# The new project system does not support designers. This blocks our ability to make XAML # changes through the designer. A rare event but necessary on occasiona. # # This script helps with the times where XAML changes are needed. It will temporarily revert # the projects which have XAML files to the legacy project system. The XAML edits can then # be processed and the coversion can be reverted. # # Bug tracking project system getting designer support # https://github.com/dotnet/project-system/issues/1467 [CmdletBinding(PositionalBinding=$false)] param () Set-StrictMode -version 2.0 $ErrorActionPreference = "Stop" $projectList = @( 'src\VisualStudio\Core\Impl\ServicesVisualStudioImpl.csproj', 'src\VisualStudio\CSharp\Impl\CSharpVisualStudio.csproj', 'src\VisualStudio\VisualBasic\Impl\BasicVisualStudio.vbproj', 'src\EditorFeatures\Core\EditorFeatures.csproj', 'src\VisualStudio\Core\Def\ServicesVisualStudio.csproj') # Edit all of the project files to no longer have a TargetFramework element. This is what # causes the selector to use the new project system. function Change-ProjectFiles() { foreach ($proj in $projectList) { $proj = Join-Path $RepoRoot $proj $lines = Get-Content $proj for ($i = 0; $i -lt $lines.Length; $i++) { $line = $lines[$i] if ($line -match ".*TargetFramework") { $lines[$i] = "<!-- DO NOT MERGE --> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion>" } } [IO.File]::WriteAllLines($proj, $lines) } } # Change the solution file to use the legacy project system GUID. function Change-Solution() { $solution = Join-Path $RepoRoot "Roslyn.sln" $lines = Get-Content $solution for ($i = 0; $i -lt $lines.Length; $i++) { $line = $lines[$i] foreach ($proj in $projectList) { if ($line -like "*$proj*") { Write-Host "Found $line" $ext = [IO.Path]::GetExtension($proj) if ($ext -eq ".csproj") { $oldGuid = "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC" $newGuid = "9A19103F-16F7-4668-BE54-9A1E7A4F7556" } else { $oldGuid = "F184B08F-C81C-45F6-A57F-5ABD9991F28F" $newGuid = "778DAE3C-4631-46EA-AA77-85C1314464D9" } $line = $line.Replace($newGuid, $oldGuid) Write-Host "New Line $line" $lines[$i] = $line } } } [IO.File]::WriteAllLines($solution, $lines) } try { . (Join-Path $PSScriptRoot "build-utils.ps1") Push-Location $RepoRoot Change-ProjectFiles Change-Solution exit 0 } catch { Write-Host $_ Write-Host $_.Exception Write-Host $_.ScriptStackTrace exit 1 } finally { Pop-Location }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/Core/CodeAnalysisTest/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/cibuild.sh
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" # resolve $SOURCE until the file is no longer a symlink while [[ -h $source ]]; do scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" source="$(readlink "$source")" # if $source was a relative symlink, we need to resolve it relative to the path where # the symlink file was located [[ $source != /* ]] && source="$scriptroot/$source" done scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" . "$scriptroot/build.sh" --restore --build --test --pack --publish --ci $@
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" # resolve $SOURCE until the file is no longer a symlink while [[ -h $source ]]; do scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" source="$(readlink "$source")" # if $source was a relative symlink, we need to resolve it relative to the path where # the symlink file was located [[ $source != /* ]] && source="$scriptroot/$source" done scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" . "$scriptroot/build.sh" --restore --build --test --pack --publish --ci $@
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/CSharpTest/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Deployment/Properties/launchSettings.json
{ "profiles": { "Visual Studio Extension": { "commandName": "Executable", "executablePath": "$(DevEnvDir)devenv.exe", "commandLineArgs": "/rootsuffix $(VSSDKTargetPlatformRegRootSuffix) /log" }, "Visual Studio Extension (with ServiceHub Debugging)": { "commandName": "Executable", "executablePath": "$(DevEnvDir)devenv.exe", "commandLineArgs": "/rootsuffix $(VSSDKTargetPlatformRegRootSuffix) /log", "environmentVariables": { "SERVICEHUBDEBUGHOSTONSTARTUP": "All" } }, "Visual Studio Extension (with Native Debugging)": { "commandName": "Executable", "executablePath": "$(DevEnvDir)devenv.exe", "commandLineArgs": "/rootsuffix $(VSSDKTargetPlatformRegRootSuffix) /log", "nativeDebugging": true } } }
{ "profiles": { "Visual Studio Extension": { "commandName": "Executable", "executablePath": "$(DevEnvDir)devenv.exe", "commandLineArgs": "/rootsuffix $(VSSDKTargetPlatformRegRootSuffix) /log" }, "Visual Studio Extension (with ServiceHub Debugging)": { "commandName": "Executable", "executablePath": "$(DevEnvDir)devenv.exe", "commandLineArgs": "/rootsuffix $(VSSDKTargetPlatformRegRootSuffix) /log", "environmentVariables": { "SERVICEHUBDEBUGHOSTONSTARTUP": "All" } }, "Visual Studio Extension (with Native Debugging)": { "commandName": "Executable", "executablePath": "$(DevEnvDir)devenv.exe", "commandLineArgs": "/rootsuffix $(VSSDKTargetPlatformRegRootSuffix) /log", "nativeDebugging": true } } }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/templates/steps/telemetry-end.yml
parameters: maxRetries: 5 retryDelay: 10 # in seconds steps: - bash: | if [ "$AGENT_JOBSTATUS" = "Succeeded" ] || [ "$AGENT_JOBSTATUS" = "PartiallySucceeded" ]; then errorCount=0 else errorCount=1 fi warningCount=0 curlStatus=1 retryCount=0 # retry loop to harden against spotty telemetry connections # we don't retry successes and 4xx client errors until [[ $curlStatus -eq 0 || ( $curlStatus -ge 400 && $curlStatus -le 499 ) || $retryCount -ge $MaxRetries ]] do if [ $retryCount -gt 0 ]; then echo "Failed to send telemetry to Helix; waiting $RetryDelay seconds before retrying..." sleep $RetryDelay fi # create a temporary file for curl output res=`mktemp` curlResult=` curl --verbose --output $res --write-out "%{http_code}"\ -H 'Content-Type: application/json' \ -H "X-Helix-Job-Token: $Helix_JobToken" \ -H 'Content-Length: 0' \ -X POST -G "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$Helix_WorkItemId/finish" \ --data-urlencode "errorCount=$errorCount" \ --data-urlencode "warningCount=$warningCount"` curlStatus=$? if [ $curlStatus -eq 0 ]; then if [ $curlResult -gt 299 ] || [ $curlResult -lt 200 ]; then curlStatus=$curlResult fi fi let retryCount++ done if [ $curlStatus -ne 0 ]; then echo "Failed to Send Build Finish information after $retryCount retries" vstsLogOutput="vso[task.logissue type=error;sourcepath=templates/steps/telemetry-end.yml;code=1;]Failed to Send Build Finish information: $curlStatus" echo "##$vstsLogOutput" exit 1 fi displayName: Send Unix Build End Telemetry env: # defined via VSTS variables in start-job.sh Helix_JobToken: $(Helix_JobToken) Helix_WorkItemId: $(Helix_WorkItemId) MaxRetries: ${{ parameters.maxRetries }} RetryDelay: ${{ parameters.retryDelay }} condition: and(always(), ne(variables['Agent.Os'], 'Windows_NT')) - powershell: | if (($env:Agent_JobStatus -eq 'Succeeded') -or ($env:Agent_JobStatus -eq 'PartiallySucceeded')) { $ErrorCount = 0 } else { $ErrorCount = 1 } $WarningCount = 0 # Basic retry loop to harden against server flakiness $retryCount = 0 while ($retryCount -lt $env:MaxRetries) { try { Invoke-RestMethod -Uri "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$env:Helix_WorkItemId/finish?errorCount=$ErrorCount&warningCount=$WarningCount" -Method Post -ContentType "application/json" -Body "" ` -Headers @{ 'X-Helix-Job-Token'=$env:Helix_JobToken } break } catch { $statusCode = $_.Exception.Response.StatusCode.value__ if ($statusCode -ge 400 -and $statusCode -le 499) { Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix (status code $statusCode); not retrying (4xx client error)" Write-Host "##vso[task.logissue]error ", $_.Exception.GetType().FullName, $_.Exception.Message exit 1 } Write-Host "Failed to send telemetry to Helix (status code $statusCode); waiting $env:RetryDelay seconds before retrying..." $retryCount++ sleep $env:RetryDelay continue } } if ($retryCount -ge $env:MaxRetries) { Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix after $retryCount retries." exit 1 } displayName: Send Windows Build End Telemetry env: # defined via VSTS variables in start-job.ps1 Helix_JobToken: $(Helix_JobToken) Helix_WorkItemId: $(Helix_WorkItemId) MaxRetries: ${{ parameters.maxRetries }} RetryDelay: ${{ parameters.retryDelay }} condition: and(always(),eq(variables['Agent.Os'], 'Windows_NT'))
parameters: maxRetries: 5 retryDelay: 10 # in seconds steps: - bash: | if [ "$AGENT_JOBSTATUS" = "Succeeded" ] || [ "$AGENT_JOBSTATUS" = "PartiallySucceeded" ]; then errorCount=0 else errorCount=1 fi warningCount=0 curlStatus=1 retryCount=0 # retry loop to harden against spotty telemetry connections # we don't retry successes and 4xx client errors until [[ $curlStatus -eq 0 || ( $curlStatus -ge 400 && $curlStatus -le 499 ) || $retryCount -ge $MaxRetries ]] do if [ $retryCount -gt 0 ]; then echo "Failed to send telemetry to Helix; waiting $RetryDelay seconds before retrying..." sleep $RetryDelay fi # create a temporary file for curl output res=`mktemp` curlResult=` curl --verbose --output $res --write-out "%{http_code}"\ -H 'Content-Type: application/json' \ -H "X-Helix-Job-Token: $Helix_JobToken" \ -H 'Content-Length: 0' \ -X POST -G "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$Helix_WorkItemId/finish" \ --data-urlencode "errorCount=$errorCount" \ --data-urlencode "warningCount=$warningCount"` curlStatus=$? if [ $curlStatus -eq 0 ]; then if [ $curlResult -gt 299 ] || [ $curlResult -lt 200 ]; then curlStatus=$curlResult fi fi let retryCount++ done if [ $curlStatus -ne 0 ]; then echo "Failed to Send Build Finish information after $retryCount retries" vstsLogOutput="vso[task.logissue type=error;sourcepath=templates/steps/telemetry-end.yml;code=1;]Failed to Send Build Finish information: $curlStatus" echo "##$vstsLogOutput" exit 1 fi displayName: Send Unix Build End Telemetry env: # defined via VSTS variables in start-job.sh Helix_JobToken: $(Helix_JobToken) Helix_WorkItemId: $(Helix_WorkItemId) MaxRetries: ${{ parameters.maxRetries }} RetryDelay: ${{ parameters.retryDelay }} condition: and(always(), ne(variables['Agent.Os'], 'Windows_NT')) - powershell: | if (($env:Agent_JobStatus -eq 'Succeeded') -or ($env:Agent_JobStatus -eq 'PartiallySucceeded')) { $ErrorCount = 0 } else { $ErrorCount = 1 } $WarningCount = 0 # Basic retry loop to harden against server flakiness $retryCount = 0 while ($retryCount -lt $env:MaxRetries) { try { Invoke-RestMethod -Uri "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$env:Helix_WorkItemId/finish?errorCount=$ErrorCount&warningCount=$WarningCount" -Method Post -ContentType "application/json" -Body "" ` -Headers @{ 'X-Helix-Job-Token'=$env:Helix_JobToken } break } catch { $statusCode = $_.Exception.Response.StatusCode.value__ if ($statusCode -ge 400 -and $statusCode -le 499) { Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix (status code $statusCode); not retrying (4xx client error)" Write-Host "##vso[task.logissue]error ", $_.Exception.GetType().FullName, $_.Exception.Message exit 1 } Write-Host "Failed to send telemetry to Helix (status code $statusCode); waiting $env:RetryDelay seconds before retrying..." $retryCount++ sleep $env:RetryDelay continue } } if ($retryCount -ge $env:MaxRetries) { Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix after $retryCount retries." exit 1 } displayName: Send Windows Build End Telemetry env: # defined via VSTS variables in start-job.ps1 Helix_JobToken: $(Helix_JobToken) Helix_WorkItemId: $(Helix_WorkItemId) MaxRetries: ${{ parameters.maxRetries }} RetryDelay: ${{ parameters.retryDelay }} condition: and(always(),eq(variables['Agent.Os'], 'Windows_NT'))
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/native/install-cmake-test.sh
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" . $scriptroot/common-library.sh base_uri= install_path= version= clean=false force=false download_retries=5 retry_wait_time_seconds=30 while (($# > 0)); do lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" case $lowerI in --baseuri) base_uri=$2 shift 2 ;; --installpath) install_path=$2 shift 2 ;; --version) version=$2 shift 2 ;; --clean) clean=true shift 1 ;; --force) force=true shift 1 ;; --downloadretries) download_retries=$2 shift 2 ;; --retrywaittimeseconds) retry_wait_time_seconds=$2 shift 2 ;; --help) echo "Common settings:" echo " --baseuri <value> Base file directory or Url wrom which to acquire tool archives" echo " --installpath <value> Base directory to install native tool to" echo " --clean Don't install the tool, just clean up the current install of the tool" echo " --force Force install of tools even if they previously exist" echo " --help Print help and exit" echo "" echo "Advanced settings:" echo " --downloadretries Total number of retry attempts" echo " --retrywaittimeseconds Wait time between retry attempts in seconds" echo "" exit 0 ;; esac done tool_name="cmake-test" tool_os=$(GetCurrentOS) tool_folder="$(echo $tool_os | tr "[:upper:]" "[:lower:]")" tool_arch="x86_64" tool_name_moniker="$tool_name-$version-$tool_os-$tool_arch" tool_install_directory="$install_path/$tool_name/$version" tool_file_path="$tool_install_directory/$tool_name_moniker/bin/$tool_name" shim_path="$install_path/$tool_name.sh" uri="${base_uri}/$tool_folder/$tool_name/$tool_name_moniker.tar.gz" # Clean up tool and installers if [[ $clean = true ]]; then echo "Cleaning $tool_install_directory" if [[ -d $tool_install_directory ]]; then rm -rf $tool_install_directory fi echo "Cleaning $shim_path" if [[ -f $shim_path ]]; then rm -rf $shim_path fi tool_temp_path=$(GetTempPathFileName $uri) echo "Cleaning $tool_temp_path" if [[ -f $tool_temp_path ]]; then rm -rf $tool_temp_path fi exit 0 fi # Install tool if [[ -f $tool_file_path ]] && [[ $force = false ]]; then echo "$tool_name ($version) already exists, skipping install" exit 0 fi DownloadAndExtract $uri $tool_install_directory $force $download_retries $retry_wait_time_seconds if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Installation failed' exit 1 fi # Generate Shim # Always rewrite shims so that we are referencing the expected version NewScriptShim $shim_path $tool_file_path true if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Shim generation failed' exit 1 fi exit 0
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" . $scriptroot/common-library.sh base_uri= install_path= version= clean=false force=false download_retries=5 retry_wait_time_seconds=30 while (($# > 0)); do lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" case $lowerI in --baseuri) base_uri=$2 shift 2 ;; --installpath) install_path=$2 shift 2 ;; --version) version=$2 shift 2 ;; --clean) clean=true shift 1 ;; --force) force=true shift 1 ;; --downloadretries) download_retries=$2 shift 2 ;; --retrywaittimeseconds) retry_wait_time_seconds=$2 shift 2 ;; --help) echo "Common settings:" echo " --baseuri <value> Base file directory or Url wrom which to acquire tool archives" echo " --installpath <value> Base directory to install native tool to" echo " --clean Don't install the tool, just clean up the current install of the tool" echo " --force Force install of tools even if they previously exist" echo " --help Print help and exit" echo "" echo "Advanced settings:" echo " --downloadretries Total number of retry attempts" echo " --retrywaittimeseconds Wait time between retry attempts in seconds" echo "" exit 0 ;; esac done tool_name="cmake-test" tool_os=$(GetCurrentOS) tool_folder="$(echo $tool_os | tr "[:upper:]" "[:lower:]")" tool_arch="x86_64" tool_name_moniker="$tool_name-$version-$tool_os-$tool_arch" tool_install_directory="$install_path/$tool_name/$version" tool_file_path="$tool_install_directory/$tool_name_moniker/bin/$tool_name" shim_path="$install_path/$tool_name.sh" uri="${base_uri}/$tool_folder/$tool_name/$tool_name_moniker.tar.gz" # Clean up tool and installers if [[ $clean = true ]]; then echo "Cleaning $tool_install_directory" if [[ -d $tool_install_directory ]]; then rm -rf $tool_install_directory fi echo "Cleaning $shim_path" if [[ -f $shim_path ]]; then rm -rf $shim_path fi tool_temp_path=$(GetTempPathFileName $uri) echo "Cleaning $tool_temp_path" if [[ -f $tool_temp_path ]]; then rm -rf $tool_temp_path fi exit 0 fi # Install tool if [[ -f $tool_file_path ]] && [[ $force = false ]]; then echo "$tool_name ($version) already exists, skipping install" exit 0 fi DownloadAndExtract $uri $tool_install_directory $force $download_retries $retry_wait_time_seconds if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Installation failed' exit 1 fi # Generate Shim # Always rewrite shims so that we are referencing the expected version NewScriptShim $shim_path $tool_file_path true if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Shim generation failed' exit 1 fi exit 0
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/CoreTest/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Setup/PowerShell/uninstall.ps1
param($installPath, $toolsPath, $package, $project) if($project.Object.SupportsPackageDependencyResolution) { if($project.Object.SupportsPackageDependencyResolution()) { # Do not uninstall analyzers via uninstall.ps1, instead let the project system handle it. return } } $analyzersPaths = Join-Path (Join-Path (Split-Path -Path $toolsPath -Parent) "analyzers") * -Resolve foreach($analyzersPath in $analyzersPaths) { # Uninstall the language agnostic analyzers. if (Test-Path $analyzersPath) { foreach ($analyzerFilePath in Get-ChildItem -Path "$analyzersPath\*.dll" -Exclude *.resources.dll) { if($project.Object.AnalyzerReferences) { $project.Object.AnalyzerReferences.Remove($analyzerFilePath.FullName) } } } } # $project.Type gives the language name like (C# or VB.NET) $languageFolder = "" if($project.Type -eq "C#") { $languageFolder = "cs" } if($project.Type -eq "VB.NET") { $languageFolder = "vb" } if($languageFolder -eq "") { return } foreach($analyzersPath in $analyzersPaths) { # Uninstall language specific analyzers. $languageAnalyzersPath = join-path $analyzersPath $languageFolder if (Test-Path $languageAnalyzersPath) { foreach ($analyzerFilePath in Get-ChildItem -Path "$languageAnalyzersPath\*.dll" -Exclude *.resources.dll) { if($project.Object.AnalyzerReferences) { try { $project.Object.AnalyzerReferences.Remove($analyzerFilePath.FullName) } catch { } } } } }
param($installPath, $toolsPath, $package, $project) if($project.Object.SupportsPackageDependencyResolution) { if($project.Object.SupportsPackageDependencyResolution()) { # Do not uninstall analyzers via uninstall.ps1, instead let the project system handle it. return } } $analyzersPaths = Join-Path (Join-Path (Split-Path -Path $toolsPath -Parent) "analyzers") * -Resolve foreach($analyzersPath in $analyzersPaths) { # Uninstall the language agnostic analyzers. if (Test-Path $analyzersPath) { foreach ($analyzerFilePath in Get-ChildItem -Path "$analyzersPath\*.dll" -Exclude *.resources.dll) { if($project.Object.AnalyzerReferences) { $project.Object.AnalyzerReferences.Remove($analyzerFilePath.FullName) } } } } # $project.Type gives the language name like (C# or VB.NET) $languageFolder = "" if($project.Type -eq "C#") { $languageFolder = "cs" } if($project.Type -eq "VB.NET") { $languageFolder = "vb" } if($languageFolder -eq "") { return } foreach($analyzersPath in $analyzersPaths) { # Uninstall language specific analyzers. $languageAnalyzersPath = join-path $analyzersPath $languageFolder if (Test-Path $languageAnalyzersPath) { foreach ($analyzerFilePath in Get-ChildItem -Path "$languageAnalyzersPath\*.dll" -Exclude *.resources.dll) { if($project.Object.AnalyzerReferences) { try { $project.Object.AnalyzerReferences.Remove($analyzerFilePath.FullName) } catch { } } } } }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./restore.sh
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" # resolve $SOURCE until the file is no longer a symlink while [[ -h $source ]]; do scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" source="$(readlink "$source")" # if $source was a relative symlink, we need to resolve it relative to the path where the # symlink file was located [[ $source != /* ]] && source="$scriptroot/$source" done scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" "$scriptroot/eng/build.sh" --restore $@
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" # resolve $SOURCE until the file is no longer a symlink while [[ -h $source ]]; do scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" source="$(readlink "$source")" # if $source was a relative symlink, we need to resolve it relative to the path where the # symlink file was located [[ $source != /* ]] && source="$scriptroot/$source" done scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" "$scriptroot/eng/build.sh" --restore $@
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/pipelines/test-integration-job.yml
parameters: - name: configuration type: string default: 'Debug' - name: oop64bit # This is actually a boolean but must be defined as string. # Parameters are evaluated at compile time, but all variables are strings at compile time. # So in order to pass a parameter that comes from a variable these must be typed as string. type: string default: true - name: lspEditor type: string default: false steps: - template: checkout-windows-task.yml - task: PowerShell@2 displayName: Build and Test inputs: filePath: eng/build.ps1 arguments: -ci -restore -build -pack -sign -publish -binaryLog -configuration ${{ parameters.configuration }} -prepareMachine -testVsi -oop64bit:$${{ parameters.oop64bit }} -collectDumps -lspEditor:$${{ parameters.lspEditor }} - task: PublishTestResults@2 displayName: Publish xUnit Test Results inputs: testRunner: XUnit testResultsFiles: $(Build.SourcesDirectory)\artifacts\TestResults\${{ parameters.configuration }}\*.xml mergeTestResults: true testRunTitle: '$(System.JobAttempt)-Integration ${{ parameters.configuration }} OOP64_${{ parameters.oop64bit }}' condition: always() - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\log\${{ parameters.configuration }}' ArtifactName: '$(System.JobAttempt)-Logs ${{ parameters.configuration }} OOP64_${{ parameters.oop64bit }} LspEditor_${{ parameters.lspEditor }} $(Build.BuildNumber)' publishLocation: Container continueOnError: true condition: not(succeeded()) - task: PublishBuildArtifacts@1 displayName: Publish Screenshots inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\bin\Microsoft.VisualStudio.LanguageServices.IntegrationTests\${{ parameters.configuration }}\net472\xUnitResults' ArtifactName: '$(System.JobAttempt)-Screenshots ${{ parameters.configuration }} OOP64_${{ parameters.oop64bit }} LspEditor_${{ parameters.lspEditor }} $(Build.BuildNumber)' publishLocation: Container continueOnError: true condition: not(succeeded())
parameters: - name: configuration type: string default: 'Debug' - name: oop64bit # This is actually a boolean but must be defined as string. # Parameters are evaluated at compile time, but all variables are strings at compile time. # So in order to pass a parameter that comes from a variable these must be typed as string. type: string default: true - name: lspEditor type: string default: false steps: - template: checkout-windows-task.yml - task: PowerShell@2 displayName: Build and Test inputs: filePath: eng/build.ps1 arguments: -ci -restore -build -pack -sign -publish -binaryLog -configuration ${{ parameters.configuration }} -prepareMachine -testVsi -oop64bit:$${{ parameters.oop64bit }} -collectDumps -lspEditor:$${{ parameters.lspEditor }} - task: PublishTestResults@2 displayName: Publish xUnit Test Results inputs: testRunner: XUnit testResultsFiles: $(Build.SourcesDirectory)\artifacts\TestResults\${{ parameters.configuration }}\*.xml mergeTestResults: true testRunTitle: '$(System.JobAttempt)-Integration ${{ parameters.configuration }} OOP64_${{ parameters.oop64bit }}' condition: always() - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\log\${{ parameters.configuration }}' ArtifactName: '$(System.JobAttempt)-Logs ${{ parameters.configuration }} OOP64_${{ parameters.oop64bit }} LspEditor_${{ parameters.lspEditor }} $(Build.BuildNumber)' publishLocation: Container continueOnError: true condition: not(succeeded()) - task: PublishBuildArtifacts@1 displayName: Publish Screenshots inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\bin\Microsoft.VisualStudio.LanguageServices.IntegrationTests\${{ parameters.configuration }}\net472\xUnitResults' ArtifactName: '$(System.JobAttempt)-Screenshots ${{ parameters.configuration }} OOP64_${{ parameters.oop64bit }} LspEditor_${{ parameters.lspEditor }} $(Build.BuildNumber)' publishLocation: Container continueOnError: true condition: not(succeeded())
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/Test/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/sdl/init-sdl.ps1
Param( [string] $GuardianCliLocation, [string] $Repository, [string] $BranchName='master', [string] $WorkingDirectory, [string] $AzureDevOpsAccessToken, [string] $GuardianLoggerLevel='Standard' ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 $disableConfigureToolsetImport = $true $global:LASTEXITCODE = 0 # `tools.ps1` checks $ci to perform some actions. Since the SDL # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true . $PSScriptRoot\..\tools.ps1 # Don't display the console progress UI - it's a huge perf hit $ProgressPreference = 'SilentlyContinue' # Construct basic auth from AzDO access token; construct URI to the repository's gdn folder stored in that repository; construct location of zip file $encodedPat = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$AzureDevOpsAccessToken")) $escapedRepository = [Uri]::EscapeDataString("/$Repository/$BranchName/.gdn") $uri = "https://dev.azure.com/dnceng/internal/_apis/git/repositories/sdl-tool-cfg/Items?path=$escapedRepository&versionDescriptor[versionOptions]=0&`$format=zip&api-version=5.0" $zipFile = "$WorkingDirectory/gdn.zip" Add-Type -AssemblyName System.IO.Compression.FileSystem $gdnFolder = (Join-Path $WorkingDirectory '.gdn') try { # if the folder does not exist, we'll do a guardian init and push it to the remote repository Write-Host 'Initializing Guardian...' Write-Host "$GuardianCliLocation init --working-directory $WorkingDirectory --logger-level $GuardianLoggerLevel" & $GuardianCliLocation init --working-directory $WorkingDirectory --logger-level $GuardianLoggerLevel if ($LASTEXITCODE -ne 0) { Write-PipelineTelemetryError -Force -Category 'Build' -Message "Guardian init failed with exit code $LASTEXITCODE." ExitWithExitCode $LASTEXITCODE } # We create the mainbaseline so it can be edited later Write-Host "$GuardianCliLocation baseline --working-directory $WorkingDirectory --name mainbaseline" & $GuardianCliLocation baseline --working-directory $WorkingDirectory --name mainbaseline if ($LASTEXITCODE -ne 0) { Write-PipelineTelemetryError -Force -Category 'Build' -Message "Guardian baseline failed with exit code $LASTEXITCODE." ExitWithExitCode $LASTEXITCODE } ExitWithExitCode 0 } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 }
Param( [string] $GuardianCliLocation, [string] $Repository, [string] $BranchName='master', [string] $WorkingDirectory, [string] $AzureDevOpsAccessToken, [string] $GuardianLoggerLevel='Standard' ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 $disableConfigureToolsetImport = $true $global:LASTEXITCODE = 0 # `tools.ps1` checks $ci to perform some actions. Since the SDL # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true . $PSScriptRoot\..\tools.ps1 # Don't display the console progress UI - it's a huge perf hit $ProgressPreference = 'SilentlyContinue' # Construct basic auth from AzDO access token; construct URI to the repository's gdn folder stored in that repository; construct location of zip file $encodedPat = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$AzureDevOpsAccessToken")) $escapedRepository = [Uri]::EscapeDataString("/$Repository/$BranchName/.gdn") $uri = "https://dev.azure.com/dnceng/internal/_apis/git/repositories/sdl-tool-cfg/Items?path=$escapedRepository&versionDescriptor[versionOptions]=0&`$format=zip&api-version=5.0" $zipFile = "$WorkingDirectory/gdn.zip" Add-Type -AssemblyName System.IO.Compression.FileSystem $gdnFolder = (Join-Path $WorkingDirectory '.gdn') try { # if the folder does not exist, we'll do a guardian init and push it to the remote repository Write-Host 'Initializing Guardian...' Write-Host "$GuardianCliLocation init --working-directory $WorkingDirectory --logger-level $GuardianLoggerLevel" & $GuardianCliLocation init --working-directory $WorkingDirectory --logger-level $GuardianLoggerLevel if ($LASTEXITCODE -ne 0) { Write-PipelineTelemetryError -Force -Category 'Build' -Message "Guardian init failed with exit code $LASTEXITCODE." ExitWithExitCode $LASTEXITCODE } # We create the mainbaseline so it can be edited later Write-Host "$GuardianCliLocation baseline --working-directory $WorkingDirectory --name mainbaseline" & $GuardianCliLocation baseline --working-directory $WorkingDirectory --name mainbaseline if ($LASTEXITCODE -ne 0) { Write-PipelineTelemetryError -Force -Category 'Build' -Message "Guardian baseline failed with exit code $LASTEXITCODE." ExitWithExitCode $LASTEXITCODE } ExitWithExitCode 0 } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/enable-cross-org-publishing.ps1
param( [string] $token ) . $PSScriptRoot\pipeline-logging-functions.ps1 # Write-PipelineSetVariable will no-op if a variable named $ci is not defined # Since this script is only ever called in AzDO builds, just universally set it $ci = $true Write-PipelineSetVariable -Name 'VSS_NUGET_ACCESSTOKEN' -Value $token -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'VSS_NUGET_URI_PREFIXES' -Value 'https://dnceng.pkgs.visualstudio.com/;https://pkgs.dev.azure.com/dnceng/;https://devdiv.pkgs.visualstudio.com/;https://pkgs.dev.azure.com/devdiv/' -IsMultiJobVariable $false
param( [string] $token ) . $PSScriptRoot\pipeline-logging-functions.ps1 # Write-PipelineSetVariable will no-op if a variable named $ci is not defined # Since this script is only ever called in AzDO builds, just universally set it $ci = $true Write-PipelineSetVariable -Name 'VSS_NUGET_ACCESSTOKEN' -Value $token -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'VSS_NUGET_URI_PREFIXES' -Value 'https://dnceng.pkgs.visualstudio.com/;https://pkgs.dev.azure.com/dnceng/;https://devdiv.pkgs.visualstudio.com/;https://pkgs.dev.azure.com/devdiv/' -IsMultiJobVariable $false
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/sdl/extract-artifact-packages.ps1
param( [Parameter(Mandatory=$true)][string] $InputPath, # Full path to directory where artifact packages are stored [Parameter(Mandatory=$true)][string] $ExtractPath # Full path to directory where the packages will be extracted ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 $disableConfigureToolsetImport = $true function ExtractArtifacts { if (!(Test-Path $InputPath)) { Write-Host "Input Path does not exist: $InputPath" ExitWithExitCode 0 } $Jobs = @() Get-ChildItem "$InputPath\*.nupkg" | ForEach-Object { $Jobs += Start-Job -ScriptBlock $ExtractPackage -ArgumentList $_.FullName } foreach ($Job in $Jobs) { Wait-Job -Id $Job.Id | Receive-Job } } try { # `tools.ps1` checks $ci to perform some actions. Since the SDL # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true . $PSScriptRoot\..\tools.ps1 $ExtractPackage = { param( [string] $PackagePath # Full path to a NuGet package ) if (!(Test-Path $PackagePath)) { Write-PipelineTelemetryError -Category 'Build' -Message "Input file does not exist: $PackagePath" ExitWithExitCode 1 } $RelevantExtensions = @('.dll', '.exe', '.pdb') Write-Host -NoNewLine 'Extracting ' ([System.IO.Path]::GetFileName($PackagePath)) '...' $PackageId = [System.IO.Path]::GetFileNameWithoutExtension($PackagePath) $ExtractPath = Join-Path -Path $using:ExtractPath -ChildPath $PackageId Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Directory]::CreateDirectory($ExtractPath); try { $zip = [System.IO.Compression.ZipFile]::OpenRead($PackagePath) $zip.Entries | Where-Object {$RelevantExtensions -contains [System.IO.Path]::GetExtension($_.Name)} | ForEach-Object { $TargetFile = Join-Path -Path $ExtractPath -ChildPath $_.Name [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, $TargetFile, $true) } } catch { Write-Host $_ Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 } finally { $zip.Dispose() } } Measure-Command { ExtractArtifacts } } catch { Write-Host $_ Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 }
param( [Parameter(Mandatory=$true)][string] $InputPath, # Full path to directory where artifact packages are stored [Parameter(Mandatory=$true)][string] $ExtractPath # Full path to directory where the packages will be extracted ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 $disableConfigureToolsetImport = $true function ExtractArtifacts { if (!(Test-Path $InputPath)) { Write-Host "Input Path does not exist: $InputPath" ExitWithExitCode 0 } $Jobs = @() Get-ChildItem "$InputPath\*.nupkg" | ForEach-Object { $Jobs += Start-Job -ScriptBlock $ExtractPackage -ArgumentList $_.FullName } foreach ($Job in $Jobs) { Wait-Job -Id $Job.Id | Receive-Job } } try { # `tools.ps1` checks $ci to perform some actions. Since the SDL # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true . $PSScriptRoot\..\tools.ps1 $ExtractPackage = { param( [string] $PackagePath # Full path to a NuGet package ) if (!(Test-Path $PackagePath)) { Write-PipelineTelemetryError -Category 'Build' -Message "Input file does not exist: $PackagePath" ExitWithExitCode 1 } $RelevantExtensions = @('.dll', '.exe', '.pdb') Write-Host -NoNewLine 'Extracting ' ([System.IO.Path]::GetFileName($PackagePath)) '...' $PackageId = [System.IO.Path]::GetFileNameWithoutExtension($PackagePath) $ExtractPath = Join-Path -Path $using:ExtractPath -ChildPath $PackageId Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Directory]::CreateDirectory($ExtractPath); try { $zip = [System.IO.Compression.ZipFile]::OpenRead($PackagePath) $zip.Entries | Where-Object {$RelevantExtensions -contains [System.IO.Path]::GetExtension($_.Name)} | ForEach-Object { $TargetFile = Join-Path -Path $ExtractPath -ChildPath $_.Name [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, $TargetFile, $true) } } catch { Write-Host $_ Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 } finally { $zip.Dispose() } } Measure-Command { ExtractArtifacts } } catch { Write-Host $_ Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/cross/build-android-rootfs.sh
#!/usr/bin/env bash set -e __NDK_Version=r21 usage() { echo "Creates a toolchain and sysroot used for cross-compiling for Android." echo. echo "Usage: $0 [BuildArch] [ApiLevel]" echo. echo "BuildArch is the target architecture of Android. Currently only arm64 is supported." echo "ApiLevel is the target Android API level. API levels usually match to Android releases. See https://source.android.com/source/build-numbers.html" echo. echo "By default, the toolchain and sysroot will be generated in cross/android-rootfs/toolchain/[BuildArch]. You can change this behavior" echo "by setting the TOOLCHAIN_DIR environment variable" echo. echo "By default, the NDK will be downloaded into the cross/android-rootfs/android-ndk-$__NDK_Version directory. If you already have an NDK installation," echo "you can set the NDK_DIR environment variable to have this script use that installation of the NDK." echo "By default, this script will generate a file, android_platform, in the root of the ROOTFS_DIR directory that contains the RID for the supported and tested Android build: android.28-arm64. This file is to replace '/etc/os-release', which is not available for Android." exit 1 } __ApiLevel=28 # The minimum platform for arm64 is API level 21 but the minimum version that support glob(3) is 28. See $ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include/glob.h __BuildArch=arm64 __AndroidArch=aarch64 __AndroidToolchain=aarch64-linux-android for i in "$@" do lowerI="$(echo $i | tr "[:upper:]" "[:lower:]")" case $lowerI in -?|-h|--help) usage exit 1 ;; arm64) __BuildArch=arm64 __AndroidArch=aarch64 __AndroidToolchain=aarch64-linux-android ;; arm) __BuildArch=arm __AndroidArch=arm __AndroidToolchain=arm-linux-androideabi ;; *[0-9]) __ApiLevel=$i ;; *) __UnprocessedBuildArgs="$__UnprocessedBuildArgs $i" ;; esac done # Obtain the location of the bash script to figure out where the root of the repo is. __ScriptBaseDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" __CrossDir="$__ScriptBaseDir/../../../.tools/android-rootfs" if [[ ! -f "$__CrossDir" ]]; then mkdir -p "$__CrossDir" fi # Resolve absolute path to avoid `../` in build logs __CrossDir="$( cd "$__CrossDir" && pwd )" __NDK_Dir="$__CrossDir/android-ndk-$__NDK_Version" __lldb_Dir="$__CrossDir/lldb" __ToolchainDir="$__CrossDir/android-ndk-$__NDK_Version" if [[ -n "$TOOLCHAIN_DIR" ]]; then __ToolchainDir=$TOOLCHAIN_DIR fi if [[ -n "$NDK_DIR" ]]; then __NDK_Dir=$NDK_DIR fi echo "Target API level: $__ApiLevel" echo "Target architecture: $__BuildArch" echo "NDK location: $__NDK_Dir" echo "Target Toolchain location: $__ToolchainDir" # Download the NDK if required if [ ! -d $__NDK_Dir ]; then echo Downloading the NDK into $__NDK_Dir mkdir -p $__NDK_Dir wget -q --progress=bar:force:noscroll --show-progress https://dl.google.com/android/repository/android-ndk-$__NDK_Version-linux-x86_64.zip -O $__CrossDir/android-ndk-$__NDK_Version-linux-x86_64.zip unzip -q $__CrossDir/android-ndk-$__NDK_Version-linux-x86_64.zip -d $__CrossDir fi if [ ! -d $__lldb_Dir ]; then mkdir -p $__lldb_Dir echo Downloading LLDB into $__lldb_Dir wget -q --progress=bar:force:noscroll --show-progress https://dl.google.com/android/repository/lldb-2.3.3614996-linux-x86_64.zip -O $__CrossDir/lldb-2.3.3614996-linux-x86_64.zip unzip -q $__CrossDir/lldb-2.3.3614996-linux-x86_64.zip -d $__lldb_Dir fi echo "Download dependencies..." __TmpDir=$__CrossDir/tmp/$__BuildArch/ mkdir -p "$__TmpDir" # combined dependencies for coreclr, installer and libraries __AndroidPackages="libicu" __AndroidPackages+=" libandroid-glob" __AndroidPackages+=" liblzma" __AndroidPackages+=" krb5" __AndroidPackages+=" openssl" for path in $(wget -qO- http://termux.net/dists/stable/main/binary-$__AndroidArch/Packages |\ grep -A15 "Package: \(${__AndroidPackages// /\\|}\)" | grep -v "static\|tool" | grep Filename); do if [[ "$path" != "Filename:" ]]; then echo "Working on: $path" wget -qO- http://termux.net/$path | dpkg -x - "$__TmpDir" fi done cp -R "$__TmpDir/data/data/com.termux/files/usr/"* "$__ToolchainDir/sysroot/usr/" # Generate platform file for build.sh script to assign to __DistroRid echo "Generating platform file..." echo "RID=android.${__ApiLevel}-${__BuildArch}" > $__ToolchainDir/sysroot/android_platform echo "Now to build coreclr, libraries and installers; run:" echo ROOTFS_DIR=\$\(realpath $__ToolchainDir/sysroot\) ./build.sh --cross --arch $__BuildArch \ --subsetCategory coreclr echo ROOTFS_DIR=\$\(realpath $__ToolchainDir/sysroot\) ./build.sh --cross --arch $__BuildArch \ --subsetCategory libraries echo ROOTFS_DIR=\$\(realpath $__ToolchainDir/sysroot\) ./build.sh --cross --arch $__BuildArch \ --subsetCategory installer
#!/usr/bin/env bash set -e __NDK_Version=r21 usage() { echo "Creates a toolchain and sysroot used for cross-compiling for Android." echo. echo "Usage: $0 [BuildArch] [ApiLevel]" echo. echo "BuildArch is the target architecture of Android. Currently only arm64 is supported." echo "ApiLevel is the target Android API level. API levels usually match to Android releases. See https://source.android.com/source/build-numbers.html" echo. echo "By default, the toolchain and sysroot will be generated in cross/android-rootfs/toolchain/[BuildArch]. You can change this behavior" echo "by setting the TOOLCHAIN_DIR environment variable" echo. echo "By default, the NDK will be downloaded into the cross/android-rootfs/android-ndk-$__NDK_Version directory. If you already have an NDK installation," echo "you can set the NDK_DIR environment variable to have this script use that installation of the NDK." echo "By default, this script will generate a file, android_platform, in the root of the ROOTFS_DIR directory that contains the RID for the supported and tested Android build: android.28-arm64. This file is to replace '/etc/os-release', which is not available for Android." exit 1 } __ApiLevel=28 # The minimum platform for arm64 is API level 21 but the minimum version that support glob(3) is 28. See $ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include/glob.h __BuildArch=arm64 __AndroidArch=aarch64 __AndroidToolchain=aarch64-linux-android for i in "$@" do lowerI="$(echo $i | tr "[:upper:]" "[:lower:]")" case $lowerI in -?|-h|--help) usage exit 1 ;; arm64) __BuildArch=arm64 __AndroidArch=aarch64 __AndroidToolchain=aarch64-linux-android ;; arm) __BuildArch=arm __AndroidArch=arm __AndroidToolchain=arm-linux-androideabi ;; *[0-9]) __ApiLevel=$i ;; *) __UnprocessedBuildArgs="$__UnprocessedBuildArgs $i" ;; esac done # Obtain the location of the bash script to figure out where the root of the repo is. __ScriptBaseDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" __CrossDir="$__ScriptBaseDir/../../../.tools/android-rootfs" if [[ ! -f "$__CrossDir" ]]; then mkdir -p "$__CrossDir" fi # Resolve absolute path to avoid `../` in build logs __CrossDir="$( cd "$__CrossDir" && pwd )" __NDK_Dir="$__CrossDir/android-ndk-$__NDK_Version" __lldb_Dir="$__CrossDir/lldb" __ToolchainDir="$__CrossDir/android-ndk-$__NDK_Version" if [[ -n "$TOOLCHAIN_DIR" ]]; then __ToolchainDir=$TOOLCHAIN_DIR fi if [[ -n "$NDK_DIR" ]]; then __NDK_Dir=$NDK_DIR fi echo "Target API level: $__ApiLevel" echo "Target architecture: $__BuildArch" echo "NDK location: $__NDK_Dir" echo "Target Toolchain location: $__ToolchainDir" # Download the NDK if required if [ ! -d $__NDK_Dir ]; then echo Downloading the NDK into $__NDK_Dir mkdir -p $__NDK_Dir wget -q --progress=bar:force:noscroll --show-progress https://dl.google.com/android/repository/android-ndk-$__NDK_Version-linux-x86_64.zip -O $__CrossDir/android-ndk-$__NDK_Version-linux-x86_64.zip unzip -q $__CrossDir/android-ndk-$__NDK_Version-linux-x86_64.zip -d $__CrossDir fi if [ ! -d $__lldb_Dir ]; then mkdir -p $__lldb_Dir echo Downloading LLDB into $__lldb_Dir wget -q --progress=bar:force:noscroll --show-progress https://dl.google.com/android/repository/lldb-2.3.3614996-linux-x86_64.zip -O $__CrossDir/lldb-2.3.3614996-linux-x86_64.zip unzip -q $__CrossDir/lldb-2.3.3614996-linux-x86_64.zip -d $__lldb_Dir fi echo "Download dependencies..." __TmpDir=$__CrossDir/tmp/$__BuildArch/ mkdir -p "$__TmpDir" # combined dependencies for coreclr, installer and libraries __AndroidPackages="libicu" __AndroidPackages+=" libandroid-glob" __AndroidPackages+=" liblzma" __AndroidPackages+=" krb5" __AndroidPackages+=" openssl" for path in $(wget -qO- http://termux.net/dists/stable/main/binary-$__AndroidArch/Packages |\ grep -A15 "Package: \(${__AndroidPackages// /\\|}\)" | grep -v "static\|tool" | grep Filename); do if [[ "$path" != "Filename:" ]]; then echo "Working on: $path" wget -qO- http://termux.net/$path | dpkg -x - "$__TmpDir" fi done cp -R "$__TmpDir/data/data/com.termux/files/usr/"* "$__ToolchainDir/sysroot/usr/" # Generate platform file for build.sh script to assign to __DistroRid echo "Generating platform file..." echo "RID=android.${__ApiLevel}-${__BuildArch}" > $__ToolchainDir/sysroot/android_platform echo "Now to build coreclr, libraries and installers; run:" echo ROOTFS_DIR=\$\(realpath $__ToolchainDir/sysroot\) ./build.sh --cross --arch $__BuildArch \ --subsetCategory coreclr echo ROOTFS_DIR=\$\(realpath $__ToolchainDir/sysroot\) ./build.sh --cross --arch $__BuildArch \ --subsetCategory libraries echo ROOTFS_DIR=\$\(realpath $__ToolchainDir/sysroot\) ./build.sh --cross --arch $__BuildArch \ --subsetCategory installer
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/generate-locproject.ps1
Param( [Parameter(Mandatory=$true)][string] $SourcesDirectory, # Directory where source files live; if using a Localize directory it should live in here [string] $LanguageSet = 'VS_Main_Languages', # Language set to be used in the LocProject.json [switch] $UseCheckedInLocProjectJson, # When set, generates a LocProject.json and compares it to one that already exists in the repo; otherwise just generates one [switch] $CreateNeutralXlfs # Creates neutral xlf files. Only set to false when running locally ) # Generates LocProject.json files for the OneLocBuild task. OneLocBuildTask is described here: # https://ceapex.visualstudio.com/CEINTL/_wiki/wikis/CEINTL.wiki/107/Localization-with-OneLocBuild-Task Set-StrictMode -Version 2.0 $ErrorActionPreference = "Stop" . $PSScriptRoot\tools.ps1 Import-Module -Name (Join-Path $PSScriptRoot 'native\CommonLibrary.psm1') $exclusionsFilePath = "$SourcesDirectory\eng\Localize\LocExclusions.json" $exclusions = @{ Exclusions = @() } if (Test-Path -Path $exclusionsFilePath) { $exclusions = Get-Content "$exclusionsFilePath" | ConvertFrom-Json } Push-Location "$SourcesDirectory" # push location for Resolve-Path -Relative to work # Template files $jsonFiles = @() $jsonTemplateFiles = Get-ChildItem -Recurse -Path "$SourcesDirectory" | Where-Object { $_.FullName -Match "\.template\.config\\localize\\.+\.en\.json" } # .NET templating pattern $jsonTemplateFiles | ForEach-Object { $null = $_.Name -Match "(.+)\.[\w-]+\.json" # matches '[filename].[langcode].json $destinationFile = "$($_.Directory.FullName)\$($Matches.1).json" $jsonFiles += Copy-Item "$($_.FullName)" -Destination $destinationFile -PassThru } $jsonWinformsTemplateFiles = Get-ChildItem -Recurse -Path "$SourcesDirectory" | Where-Object { $_.FullName -Match "en\\strings\.json" } # current winforms pattern $xlfFiles = @() $allXlfFiles = Get-ChildItem -Recurse -Path "$SourcesDirectory\*\*.xlf" $langXlfFiles = @() if ($allXlfFiles) { $null = $allXlfFiles[0].FullName -Match "\.([\w-]+)\.xlf" # matches '[langcode].xlf' $firstLangCode = $Matches.1 $langXlfFiles = Get-ChildItem -Recurse -Path "$SourcesDirectory\*\*.$firstLangCode.xlf" } $langXlfFiles | ForEach-Object { $null = $_.Name -Match "(.+)\.[\w-]+\.xlf" # matches '[filename].[langcode].xlf $destinationFile = "$($_.Directory.FullName)\$($Matches.1).xlf" $xlfFiles += Copy-Item "$($_.FullName)" -Destination $destinationFile -PassThru } $locFiles = $jsonFiles + $jsonWinformsTemplateFiles + $xlfFiles $locJson = @{ Projects = @( @{ LanguageSet = $LanguageSet LocItems = @( $locFiles | ForEach-Object { $outputPath = "$(($_.DirectoryName | Resolve-Path -Relative) + "\")" $continue = $true foreach ($exclusion in $exclusions.Exclusions) { if ($outputPath.Contains($exclusion)) { $continue = $false } } $sourceFile = ($_.FullName | Resolve-Path -Relative) if (!$CreateNeutralXlfs -and $_.Extension -eq '.xlf') { Remove-Item -Path $sourceFile } if ($continue) { if ($_.Directory.Name -eq 'en' -and $_.Extension -eq '.json') { return @{ SourceFile = $sourceFile CopyOption = "LangIDOnPath" OutputPath = "$($_.Directory.Parent.FullName | Resolve-Path -Relative)\" } } else { return @{ SourceFile = $sourceFile CopyOption = "LangIDOnName" OutputPath = $outputPath } } } } ) } ) } $json = ConvertTo-Json $locJson -Depth 5 Write-Host "LocProject.json generated:`n`n$json`n`n" Pop-Location if (!$UseCheckedInLocProjectJson) { New-Item "$SourcesDirectory\eng\Localize\LocProject.json" -Force # Need this to make sure the Localize directory is created Set-Content "$SourcesDirectory\eng\Localize\LocProject.json" $json } else { New-Item "$SourcesDirectory\eng\Localize\LocProject-generated.json" -Force # Need this to make sure the Localize directory is created Set-Content "$SourcesDirectory\eng\Localize\LocProject-generated.json" $json if ((Get-FileHash "$SourcesDirectory\eng\Localize\LocProject-generated.json").Hash -ne (Get-FileHash "$SourcesDirectory\eng\Localize\LocProject.json").Hash) { Write-PipelineTelemetryError -Category "OneLocBuild" -Message "Existing LocProject.json differs from generated LocProject.json. Download LocProject-generated.json and compare them." exit 1 } else { Write-Host "Generated LocProject.json and current LocProject.json are identical." } }
Param( [Parameter(Mandatory=$true)][string] $SourcesDirectory, # Directory where source files live; if using a Localize directory it should live in here [string] $LanguageSet = 'VS_Main_Languages', # Language set to be used in the LocProject.json [switch] $UseCheckedInLocProjectJson, # When set, generates a LocProject.json and compares it to one that already exists in the repo; otherwise just generates one [switch] $CreateNeutralXlfs # Creates neutral xlf files. Only set to false when running locally ) # Generates LocProject.json files for the OneLocBuild task. OneLocBuildTask is described here: # https://ceapex.visualstudio.com/CEINTL/_wiki/wikis/CEINTL.wiki/107/Localization-with-OneLocBuild-Task Set-StrictMode -Version 2.0 $ErrorActionPreference = "Stop" . $PSScriptRoot\tools.ps1 Import-Module -Name (Join-Path $PSScriptRoot 'native\CommonLibrary.psm1') $exclusionsFilePath = "$SourcesDirectory\eng\Localize\LocExclusions.json" $exclusions = @{ Exclusions = @() } if (Test-Path -Path $exclusionsFilePath) { $exclusions = Get-Content "$exclusionsFilePath" | ConvertFrom-Json } Push-Location "$SourcesDirectory" # push location for Resolve-Path -Relative to work # Template files $jsonFiles = @() $jsonTemplateFiles = Get-ChildItem -Recurse -Path "$SourcesDirectory" | Where-Object { $_.FullName -Match "\.template\.config\\localize\\.+\.en\.json" } # .NET templating pattern $jsonTemplateFiles | ForEach-Object { $null = $_.Name -Match "(.+)\.[\w-]+\.json" # matches '[filename].[langcode].json $destinationFile = "$($_.Directory.FullName)\$($Matches.1).json" $jsonFiles += Copy-Item "$($_.FullName)" -Destination $destinationFile -PassThru } $jsonWinformsTemplateFiles = Get-ChildItem -Recurse -Path "$SourcesDirectory" | Where-Object { $_.FullName -Match "en\\strings\.json" } # current winforms pattern $xlfFiles = @() $allXlfFiles = Get-ChildItem -Recurse -Path "$SourcesDirectory\*\*.xlf" $langXlfFiles = @() if ($allXlfFiles) { $null = $allXlfFiles[0].FullName -Match "\.([\w-]+)\.xlf" # matches '[langcode].xlf' $firstLangCode = $Matches.1 $langXlfFiles = Get-ChildItem -Recurse -Path "$SourcesDirectory\*\*.$firstLangCode.xlf" } $langXlfFiles | ForEach-Object { $null = $_.Name -Match "(.+)\.[\w-]+\.xlf" # matches '[filename].[langcode].xlf $destinationFile = "$($_.Directory.FullName)\$($Matches.1).xlf" $xlfFiles += Copy-Item "$($_.FullName)" -Destination $destinationFile -PassThru } $locFiles = $jsonFiles + $jsonWinformsTemplateFiles + $xlfFiles $locJson = @{ Projects = @( @{ LanguageSet = $LanguageSet LocItems = @( $locFiles | ForEach-Object { $outputPath = "$(($_.DirectoryName | Resolve-Path -Relative) + "\")" $continue = $true foreach ($exclusion in $exclusions.Exclusions) { if ($outputPath.Contains($exclusion)) { $continue = $false } } $sourceFile = ($_.FullName | Resolve-Path -Relative) if (!$CreateNeutralXlfs -and $_.Extension -eq '.xlf') { Remove-Item -Path $sourceFile } if ($continue) { if ($_.Directory.Name -eq 'en' -and $_.Extension -eq '.json') { return @{ SourceFile = $sourceFile CopyOption = "LangIDOnPath" OutputPath = "$($_.Directory.Parent.FullName | Resolve-Path -Relative)\" } } else { return @{ SourceFile = $sourceFile CopyOption = "LangIDOnName" OutputPath = $outputPath } } } } ) } ) } $json = ConvertTo-Json $locJson -Depth 5 Write-Host "LocProject.json generated:`n`n$json`n`n" Pop-Location if (!$UseCheckedInLocProjectJson) { New-Item "$SourcesDirectory\eng\Localize\LocProject.json" -Force # Need this to make sure the Localize directory is created Set-Content "$SourcesDirectory\eng\Localize\LocProject.json" $json } else { New-Item "$SourcesDirectory\eng\Localize\LocProject-generated.json" -Force # Need this to make sure the Localize directory is created Set-Content "$SourcesDirectory\eng\Localize\LocProject-generated.json" $json if ((Get-FileHash "$SourcesDirectory\eng\Localize\LocProject-generated.json").Hash -ne (Get-FileHash "$SourcesDirectory\eng\Localize\LocProject.json").Hash) { Write-PipelineTelemetryError -Category "OneLocBuild" -Message "Existing LocProject.json differs from generated LocProject.json. Download LocProject-generated.json and compare them." exit 1 } else { Write-Host "Generated LocProject.json and current LocProject.json are identical." } }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./.vscode/tasks.json
{ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "windows": { "options": { "shell": { "executable": "cmd.exe", "args": [ "/d", "/c" ] } } }, "tasks": [ { "label": "build", "command": "./build.sh", "type": "shell", "args": [ ], "windows": { "command": "${workspaceFolder}/build.cmd", }, "problemMatcher": "$msCompile", "group": "build" }, { "label": "build with analyzers", "command": "./build.sh", "type": "shell", "args": [ "--runAnalyzers" ], "windows": { "command": "${workspaceFolder}/build.cmd", "args": [ "-runAnalyzers" ], }, "problemMatcher": "$msCompile", "group": "build" }, { "label": "build csc", "command": "${workspaceFolder}/.dotnet/dotnet", "type": "shell", "args": [ "msbuild", "-p:RunAnalyzersDuringBuild=false", "-p:GenerateFullPaths=true", "src/Compilers/CSharp/csc/csc.csproj" ], "problemMatcher": "$msCompile", "group": "build" }, { "label": "build current project", "type": "shell", "command": "${workspaceFolder}/.dotnet/dotnet", "args": [ "pwsh", "${workspaceFolder}/scripts/vscode-build.ps1", "-filePath", "${file}", "-msbuildEngine", "dotnet" ], "windows": { "command": "powershell", "args": [ "${workspaceFolder}/scripts/vscode-build.ps1", "-filePath", "${file}", "-msbuildEngine", "dotnet" ], }, "problemMatcher": "$msCompile", "group": "build" }, { "label": "msbuild current project", "type": "shell", "command": "echo 'Task not supported on this OS'", "windows": { "command": "powershell", "args": [ "${workspaceFolder}/scripts/vscode-build.ps1", "-filePath", "${file}", "-msbuildEngine", "vs" ], }, "problemMatcher": "$msCompile", "group": "build" }, { "label": "generate compiler code", "command": "${workspaceFolder}/.dotnet/dotnet", "type": "shell", "args": [ "pwsh", "${workspaceFolder}/eng/generate-compiler-code.ps1" ], "problemMatcher": "$msCompile", "group": "build" }, { "label": "update xlf files", "command": "./build.sh", "type": "shell", "windows": { "command": "${workspaceFolder}/build.cmd" }, "options": { "env": { "UpdateXlfOnBuild": "true" } }, "problemMatcher": "$msCompile", "group": "build" }, { "label": "run tests in current file (netcoreapp3.1)", "command": "${workspaceFolder}/.dotnet/dotnet", "type": "shell", "args": [ "pwsh", "${workspaceFolder}/scripts/vscode-run-tests.ps1", "-filePath", "${file}", "-msbuildEngine", "dotnet", "-framework", "netcoreapp3.1", "-filter", "${fileBasenameNoExtension}" ], "problemMatcher": "$msCompile", "group": "test" }, { "label": "run tests in current project (netcoreapp3.1)", "command": "${workspaceFolder}/.dotnet/dotnet", "type": "shell", "args": [ "pwsh", "${workspaceFolder}/scripts/vscode-run-tests.ps1", "-filePath", "${file}", "-msbuildEngine", "dotnet", "-framework", "netcoreapp3.1" ], "problemMatcher": "$msCompile", "group": "test" }, { "label": "run tests in current file (all frameworks)", "command": "${workspaceFolder}/.dotnet/dotnet", "type": "shell", "args": [ "pwsh", "${workspaceFolder}/scripts/vscode-run-tests.ps1", "-filePath", "${file}", "-filter", "${fileBasenameNoExtension}" ], "problemMatcher": "$msCompile", "group": "test" }, { "label": "run tests in current project (all frameworks)", "command": "${workspaceFolder}/.dotnet/dotnet", "type": "shell", "args": [ "pwsh", "${workspaceFolder}/scripts/vscode-run-tests.ps1", "-filePath", "${file}" ], "problemMatcher": "$msCompile", "group": "test" } ] }
{ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "windows": { "options": { "shell": { "executable": "cmd.exe", "args": [ "/d", "/c" ] } } }, "tasks": [ { "label": "build", "command": "./build.sh", "type": "shell", "args": [ ], "windows": { "command": "${workspaceFolder}/build.cmd", }, "problemMatcher": "$msCompile", "group": "build" }, { "label": "build with analyzers", "command": "./build.sh", "type": "shell", "args": [ "--runAnalyzers" ], "windows": { "command": "${workspaceFolder}/build.cmd", "args": [ "-runAnalyzers" ], }, "problemMatcher": "$msCompile", "group": "build" }, { "label": "build csc", "command": "${workspaceFolder}/.dotnet/dotnet", "type": "shell", "args": [ "msbuild", "-p:RunAnalyzersDuringBuild=false", "-p:GenerateFullPaths=true", "src/Compilers/CSharp/csc/csc.csproj" ], "problemMatcher": "$msCompile", "group": "build" }, { "label": "build current project", "type": "shell", "command": "${workspaceFolder}/.dotnet/dotnet", "args": [ "pwsh", "${workspaceFolder}/scripts/vscode-build.ps1", "-filePath", "${file}", "-msbuildEngine", "dotnet" ], "windows": { "command": "powershell", "args": [ "${workspaceFolder}/scripts/vscode-build.ps1", "-filePath", "${file}", "-msbuildEngine", "dotnet" ], }, "problemMatcher": "$msCompile", "group": "build" }, { "label": "msbuild current project", "type": "shell", "command": "echo 'Task not supported on this OS'", "windows": { "command": "powershell", "args": [ "${workspaceFolder}/scripts/vscode-build.ps1", "-filePath", "${file}", "-msbuildEngine", "vs" ], }, "problemMatcher": "$msCompile", "group": "build" }, { "label": "generate compiler code", "command": "${workspaceFolder}/.dotnet/dotnet", "type": "shell", "args": [ "pwsh", "${workspaceFolder}/eng/generate-compiler-code.ps1" ], "problemMatcher": "$msCompile", "group": "build" }, { "label": "update xlf files", "command": "./build.sh", "type": "shell", "windows": { "command": "${workspaceFolder}/build.cmd" }, "options": { "env": { "UpdateXlfOnBuild": "true" } }, "problemMatcher": "$msCompile", "group": "build" }, { "label": "run tests in current file (netcoreapp3.1)", "command": "${workspaceFolder}/.dotnet/dotnet", "type": "shell", "args": [ "pwsh", "${workspaceFolder}/scripts/vscode-run-tests.ps1", "-filePath", "${file}", "-msbuildEngine", "dotnet", "-framework", "netcoreapp3.1", "-filter", "${fileBasenameNoExtension}" ], "problemMatcher": "$msCompile", "group": "test" }, { "label": "run tests in current project (netcoreapp3.1)", "command": "${workspaceFolder}/.dotnet/dotnet", "type": "shell", "args": [ "pwsh", "${workspaceFolder}/scripts/vscode-run-tests.ps1", "-filePath", "${file}", "-msbuildEngine", "dotnet", "-framework", "netcoreapp3.1" ], "problemMatcher": "$msCompile", "group": "test" }, { "label": "run tests in current file (all frameworks)", "command": "${workspaceFolder}/.dotnet/dotnet", "type": "shell", "args": [ "pwsh", "${workspaceFolder}/scripts/vscode-run-tests.ps1", "-filePath", "${file}", "-filter", "${fileBasenameNoExtension}" ], "problemMatcher": "$msCompile", "group": "test" }, { "label": "run tests in current project (all frameworks)", "command": "${workspaceFolder}/.dotnet/dotnet", "type": "shell", "args": [ "pwsh", "${workspaceFolder}/scripts/vscode-run-tests.ps1", "-filePath", "${file}" ], "problemMatcher": "$msCompile", "group": "test" } ] }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/templates/steps/publish-logs.yml
parameters: StageLabel: '' JobLabel: '' steps: - task: Powershell@2 displayName: Prepare Binlogs to Upload inputs: targetType: inline script: | New-Item -ItemType Directory $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ Move-Item -Path $(Build.SourcesDirectory)/artifacts/log/Debug/* $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ continueOnError: true condition: always() - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)/PostBuildLogs' PublishLocation: Container ArtifactName: PostBuildLogs continueOnError: true condition: always()
parameters: StageLabel: '' JobLabel: '' steps: - task: Powershell@2 displayName: Prepare Binlogs to Upload inputs: targetType: inline script: | New-Item -ItemType Directory $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ Move-Item -Path $(Build.SourcesDirectory)/artifacts/log/Debug/* $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ continueOnError: true condition: always() - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)/PostBuildLogs' PublishLocation: Container ArtifactName: PostBuildLogs continueOnError: true condition: always()
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/MSBuildTest/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/test-rebuild.ps1
<# This script tests that Roslyn artifacts are rebuildable--i.e. that the source code and resources can be identified #> [CmdletBinding(PositionalBinding=$false)] param( [string]$configuration = "Debug", [switch]$ci = $false, [switch]$useGlobalNuGetCache = $true, [switch]$noBuild = $false, [switch]$help) Set-StrictMode -version 2.0 $ErrorActionPreference="Stop" function Print-Usage() { Write-Host "Usage: test-rebuild.ps1" Write-Host " -configuration Build configuration ('Debug' or 'Release')" Write-Host " -ci Set when running on CI server" Write-Host " -useGlobalNuGetCache Use global NuGet cache." Write-Host " -noBuild If set, skips running a bootstrap build before running the rebuild" Write-Host " -help Print help and exit" } try { if ($help) { Print-Usage exit 0 } . (Join-Path $PSScriptRoot "build-utils.ps1") Push-Location $RepoRoot if (-not $noBuild) { Write-Host "Building Roslyn" Exec-Block { & (Join-Path $PSScriptRoot "build.ps1") -build -bootstrap -ci:$ci -useGlobalNuGetCache:$useGlobalNuGetCache -configuration:$configuration -pack -binaryLog } } $dotnetInstallDir = (InitializeDotNetCli -install:$true) $rebuildArgs = ("--verbose" + " --assembliesPath `"$ArtifactsDir/obj/`"" + # Rebuilds with output differences " --exclude net472\Microsoft.CodeAnalysis.EditorFeatures.Wpf.dll" + " --exclude net472\Microsoft.VisualStudio.LanguageServices.CSharp.dll" + " --exclude net472\Microsoft.VisualStudio.LanguageServices.dll" + " --exclude net472\Microsoft.VisualStudio.LanguageServices.Implementation.dll" + " --exclude net472\Microsoft.VisualStudio.LanguageServices.VisualBasic.dll" + " --exclude net472\Roslyn.Hosting.Diagnostics.dll" + " --exclude net472\Roslyn.VisualStudio.DiagnosticsWindow.dll" + # Rebuilds with compilation errors # Rebuilds with missing references # Rebuilds with other issues " --exclude net472\Microsoft.CodeAnalysis.EditorFeatures2.UnitTests.dll" + " --exclude netcoreapp3.1\Microsoft.CodeAnalysis.Collections.Package.dll" + " --exclude netstandard2.0\Microsoft.CodeAnalysis.Collections.Package.dll" + " --exclude net45\Microsoft.CodeAnalysis.Debugging.Package.dll" + " --exclude netstandard1.3\Microsoft.CodeAnalysis.Debugging.Package.dll" + " --exclude net45\Microsoft.CodeAnalysis.PooledObjects.Package.dll" + " --exclude netstandard1.3\Microsoft.CodeAnalysis.PooledObjects.Package.dll" + " --exclude netcoreapp3.1\Microsoft.CodeAnalysis.Workspaces.UnitTests.dll" + " --exclude net472\Zip\tools\vsixexpinstaller\System.ValueTuple.dll" + " --exclude net472\Zip\tools\vsixexpinstaller\VSIXExpInstaller.exe" + " --debugPath `"$ArtifactsDir/BuildValidator`"" + " --sourcePath `"$RepoRoot/`"" + " --referencesPath `"$ArtifactsDir/bin`"" + " --referencesPath `"$dotnetInstallDir/packs`"") Exec-Console "$ArtifactsDir/bin/BuildValidator/$configuration/net472/BuildValidator.exe" $rebuildArgs exit 0 } catch [exception] { Write-Host $_ Write-Host $_.Exception exit 1 } finally { Pop-Location }
<# This script tests that Roslyn artifacts are rebuildable--i.e. that the source code and resources can be identified #> [CmdletBinding(PositionalBinding=$false)] param( [string]$configuration = "Debug", [switch]$ci = $false, [switch]$useGlobalNuGetCache = $true, [switch]$noBuild = $false, [switch]$help) Set-StrictMode -version 2.0 $ErrorActionPreference="Stop" function Print-Usage() { Write-Host "Usage: test-rebuild.ps1" Write-Host " -configuration Build configuration ('Debug' or 'Release')" Write-Host " -ci Set when running on CI server" Write-Host " -useGlobalNuGetCache Use global NuGet cache." Write-Host " -noBuild If set, skips running a bootstrap build before running the rebuild" Write-Host " -help Print help and exit" } try { if ($help) { Print-Usage exit 0 } . (Join-Path $PSScriptRoot "build-utils.ps1") Push-Location $RepoRoot if (-not $noBuild) { Write-Host "Building Roslyn" Exec-Block { & (Join-Path $PSScriptRoot "build.ps1") -build -bootstrap -ci:$ci -useGlobalNuGetCache:$useGlobalNuGetCache -configuration:$configuration -pack -binaryLog } } $dotnetInstallDir = (InitializeDotNetCli -install:$true) $rebuildArgs = ("--verbose" + " --assembliesPath `"$ArtifactsDir/obj/`"" + # Rebuilds with output differences " --exclude net472\Microsoft.CodeAnalysis.EditorFeatures.Wpf.dll" + " --exclude net472\Microsoft.VisualStudio.LanguageServices.CSharp.dll" + " --exclude net472\Microsoft.VisualStudio.LanguageServices.dll" + " --exclude net472\Microsoft.VisualStudio.LanguageServices.Implementation.dll" + " --exclude net472\Microsoft.VisualStudio.LanguageServices.VisualBasic.dll" + " --exclude net472\Roslyn.Hosting.Diagnostics.dll" + " --exclude net472\Roslyn.VisualStudio.DiagnosticsWindow.dll" + # Rebuilds with compilation errors # Rebuilds with missing references # Rebuilds with other issues " --exclude net472\Microsoft.CodeAnalysis.EditorFeatures2.UnitTests.dll" + " --exclude netcoreapp3.1\Microsoft.CodeAnalysis.Collections.Package.dll" + " --exclude netstandard2.0\Microsoft.CodeAnalysis.Collections.Package.dll" + " --exclude net45\Microsoft.CodeAnalysis.Debugging.Package.dll" + " --exclude netstandard1.3\Microsoft.CodeAnalysis.Debugging.Package.dll" + " --exclude net45\Microsoft.CodeAnalysis.PooledObjects.Package.dll" + " --exclude netstandard1.3\Microsoft.CodeAnalysis.PooledObjects.Package.dll" + " --exclude netcoreapp3.1\Microsoft.CodeAnalysis.Workspaces.UnitTests.dll" + " --exclude net472\Zip\tools\vsixexpinstaller\System.ValueTuple.dll" + " --exclude net472\Zip\tools\vsixexpinstaller\VSIXExpInstaller.exe" + " --debugPath `"$ArtifactsDir/BuildValidator`"" + " --sourcePath `"$RepoRoot/`"" + " --referencesPath `"$ArtifactsDir/bin`"" + " --referencesPath `"$dotnetInstallDir/packs`"") Exec-Console "$ArtifactsDir/bin/BuildValidator/$configuration/net472/BuildValidator.exe" $rebuildArgs exit 0 } catch [exception] { Write-Host $_ Write-Host $_.Exception exit 1 } finally { Pop-Location }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./azure-pipelines-integration.yml
# Branches that trigger a build on commit trigger: - main - main-vs-deps - release/* - features/* - demos/* # Branches that trigger builds on PR pr: - main - main-vs-deps - release/* - features/* - demos/* jobs: - job: VS_Integration pool: name: $(poolName) queue: $(queueName) strategy: maxParallel: 4 matrix: debug_32: _configuration: Debug _oop64bit: false debug_64: _configuration: Debug _oop64bit: true release_32: _configuration: Release _oop64bit: false release_64: _configuration: Release _oop64bit: true timeoutInMinutes: 135 steps: - template: eng/pipelines/test-integration-job.yml parameters: configuration: $(_configuration) oop64bit: $(_oop64bit) lspEditor: false
# Branches that trigger a build on commit trigger: - main - main-vs-deps - release/* - features/* - demos/* # Branches that trigger builds on PR pr: - main - main-vs-deps - release/* - features/* - demos/* jobs: - job: VS_Integration pool: name: $(poolName) queue: $(queueName) strategy: maxParallel: 4 matrix: debug_32: _configuration: Debug _oop64bit: false debug_64: _configuration: Debug _oop64bit: true release_32: _configuration: Release _oop64bit: false release_64: _configuration: Release _oop64bit: true timeoutInMinutes: 135 steps: - template: eng/pipelines/test-integration-job.yml parameters: configuration: $(_configuration) oop64bit: $(_oop64bit) lspEditor: false
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Interactive/HostTest/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/init-tools-native.ps1
<# .SYNOPSIS Entry point script for installing native tools .DESCRIPTION Reads $RepoRoot\global.json file to determine native assets to install and executes installers for those tools .PARAMETER BaseUri Base file directory or Url from which to acquire tool archives .PARAMETER InstallDirectory Directory to install native toolset. This is a command-line override for the default Install directory precedence order: - InstallDirectory command-line override - NETCOREENG_INSTALL_DIRECTORY environment variable - (default) %USERPROFILE%/.netcoreeng/native .PARAMETER Clean Switch specifying to not install anything, but cleanup native asset folders .PARAMETER Force Clean and then install tools .PARAMETER DownloadRetries Total number of retry attempts .PARAMETER RetryWaitTimeInSeconds Wait time between retry attempts in seconds .PARAMETER GlobalJsonFile File path to global.json file .NOTES #> [CmdletBinding(PositionalBinding=$false)] Param ( [string] $BaseUri = 'https://netcorenativeassets.blob.core.windows.net/resource-packages/external', [string] $InstallDirectory, [switch] $Clean = $False, [switch] $Force = $False, [int] $DownloadRetries = 5, [int] $RetryWaitTimeInSeconds = 30, [string] $GlobalJsonFile ) if (!$GlobalJsonFile) { $GlobalJsonFile = Join-Path (Get-Item $PSScriptRoot).Parent.Parent.FullName 'global.json' } Set-StrictMode -version 2.0 $ErrorActionPreference='Stop' . $PSScriptRoot\pipeline-logging-functions.ps1 Import-Module -Name (Join-Path $PSScriptRoot 'native\CommonLibrary.psm1') try { # Define verbose switch if undefined $Verbose = $VerbosePreference -Eq 'Continue' $EngCommonBaseDir = Join-Path $PSScriptRoot 'native\' $NativeBaseDir = $InstallDirectory if (!$NativeBaseDir) { $NativeBaseDir = CommonLibrary\Get-NativeInstallDirectory } $Env:CommonLibrary_NativeInstallDir = $NativeBaseDir $InstallBin = Join-Path $NativeBaseDir 'bin' $InstallerPath = Join-Path $EngCommonBaseDir 'install-tool.ps1' # Process tools list Write-Host "Processing $GlobalJsonFile" If (-Not (Test-Path $GlobalJsonFile)) { Write-Host "Unable to find '$GlobalJsonFile'" exit 0 } $NativeTools = Get-Content($GlobalJsonFile) -Raw | ConvertFrom-Json | Select-Object -Expand 'native-tools' -ErrorAction SilentlyContinue if ($NativeTools) { $NativeTools.PSObject.Properties | ForEach-Object { $ToolName = $_.Name $ToolVersion = $_.Value $LocalInstallerArguments = @{ ToolName = "$ToolName" } $LocalInstallerArguments += @{ InstallPath = "$InstallBin" } $LocalInstallerArguments += @{ BaseUri = "$BaseUri" } $LocalInstallerArguments += @{ CommonLibraryDirectory = "$EngCommonBaseDir" } $LocalInstallerArguments += @{ Version = "$ToolVersion" } if ($Verbose) { $LocalInstallerArguments += @{ Verbose = $True } } if (Get-Variable 'Force' -ErrorAction 'SilentlyContinue') { if($Force) { $LocalInstallerArguments += @{ Force = $True } } } if ($Clean) { $LocalInstallerArguments += @{ Clean = $True } } Write-Verbose "Installing $ToolName version $ToolVersion" Write-Verbose "Executing '$InstallerPath $($LocalInstallerArguments.Keys.ForEach({"-$_ '$($LocalInstallerArguments.$_)'"}) -join ' ')'" & $InstallerPath @LocalInstallerArguments if ($LASTEXITCODE -Ne "0") { $errMsg = "$ToolName installation failed" if ((Get-Variable 'DoNotAbortNativeToolsInstallationOnFailure' -ErrorAction 'SilentlyContinue') -and $DoNotAbortNativeToolsInstallationOnFailure) { $showNativeToolsWarning = $true if ((Get-Variable 'DoNotDisplayNativeToolsInstallationWarnings' -ErrorAction 'SilentlyContinue') -and $DoNotDisplayNativeToolsInstallationWarnings) { $showNativeToolsWarning = $false } if ($showNativeToolsWarning) { Write-Warning $errMsg } $toolInstallationFailure = $true } else { # We cannot change this to Write-PipelineTelemetryError because of https://github.com/dotnet/arcade/issues/4482 Write-Host $errMsg exit 1 } } } if ((Get-Variable 'toolInstallationFailure' -ErrorAction 'SilentlyContinue') -and $toolInstallationFailure) { # We cannot change this to Write-PipelineTelemetryError because of https://github.com/dotnet/arcade/issues/4482 Write-Host 'Native tools bootstrap failed' exit 1 } } else { Write-Host 'No native tools defined in global.json' exit 0 } if ($Clean) { exit 0 } if (Test-Path $InstallBin) { Write-Host 'Native tools are available from ' (Convert-Path -Path $InstallBin) Write-Host "##vso[task.prependpath]$(Convert-Path -Path $InstallBin)" return $InstallBin } else { Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message 'Native tools install directory does not exist, installation failed' exit 1 } exit 0 } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message $_ ExitWithExitCode 1 }
<# .SYNOPSIS Entry point script for installing native tools .DESCRIPTION Reads $RepoRoot\global.json file to determine native assets to install and executes installers for those tools .PARAMETER BaseUri Base file directory or Url from which to acquire tool archives .PARAMETER InstallDirectory Directory to install native toolset. This is a command-line override for the default Install directory precedence order: - InstallDirectory command-line override - NETCOREENG_INSTALL_DIRECTORY environment variable - (default) %USERPROFILE%/.netcoreeng/native .PARAMETER Clean Switch specifying to not install anything, but cleanup native asset folders .PARAMETER Force Clean and then install tools .PARAMETER DownloadRetries Total number of retry attempts .PARAMETER RetryWaitTimeInSeconds Wait time between retry attempts in seconds .PARAMETER GlobalJsonFile File path to global.json file .NOTES #> [CmdletBinding(PositionalBinding=$false)] Param ( [string] $BaseUri = 'https://netcorenativeassets.blob.core.windows.net/resource-packages/external', [string] $InstallDirectory, [switch] $Clean = $False, [switch] $Force = $False, [int] $DownloadRetries = 5, [int] $RetryWaitTimeInSeconds = 30, [string] $GlobalJsonFile ) if (!$GlobalJsonFile) { $GlobalJsonFile = Join-Path (Get-Item $PSScriptRoot).Parent.Parent.FullName 'global.json' } Set-StrictMode -version 2.0 $ErrorActionPreference='Stop' . $PSScriptRoot\pipeline-logging-functions.ps1 Import-Module -Name (Join-Path $PSScriptRoot 'native\CommonLibrary.psm1') try { # Define verbose switch if undefined $Verbose = $VerbosePreference -Eq 'Continue' $EngCommonBaseDir = Join-Path $PSScriptRoot 'native\' $NativeBaseDir = $InstallDirectory if (!$NativeBaseDir) { $NativeBaseDir = CommonLibrary\Get-NativeInstallDirectory } $Env:CommonLibrary_NativeInstallDir = $NativeBaseDir $InstallBin = Join-Path $NativeBaseDir 'bin' $InstallerPath = Join-Path $EngCommonBaseDir 'install-tool.ps1' # Process tools list Write-Host "Processing $GlobalJsonFile" If (-Not (Test-Path $GlobalJsonFile)) { Write-Host "Unable to find '$GlobalJsonFile'" exit 0 } $NativeTools = Get-Content($GlobalJsonFile) -Raw | ConvertFrom-Json | Select-Object -Expand 'native-tools' -ErrorAction SilentlyContinue if ($NativeTools) { $NativeTools.PSObject.Properties | ForEach-Object { $ToolName = $_.Name $ToolVersion = $_.Value $LocalInstallerArguments = @{ ToolName = "$ToolName" } $LocalInstallerArguments += @{ InstallPath = "$InstallBin" } $LocalInstallerArguments += @{ BaseUri = "$BaseUri" } $LocalInstallerArguments += @{ CommonLibraryDirectory = "$EngCommonBaseDir" } $LocalInstallerArguments += @{ Version = "$ToolVersion" } if ($Verbose) { $LocalInstallerArguments += @{ Verbose = $True } } if (Get-Variable 'Force' -ErrorAction 'SilentlyContinue') { if($Force) { $LocalInstallerArguments += @{ Force = $True } } } if ($Clean) { $LocalInstallerArguments += @{ Clean = $True } } Write-Verbose "Installing $ToolName version $ToolVersion" Write-Verbose "Executing '$InstallerPath $($LocalInstallerArguments.Keys.ForEach({"-$_ '$($LocalInstallerArguments.$_)'"}) -join ' ')'" & $InstallerPath @LocalInstallerArguments if ($LASTEXITCODE -Ne "0") { $errMsg = "$ToolName installation failed" if ((Get-Variable 'DoNotAbortNativeToolsInstallationOnFailure' -ErrorAction 'SilentlyContinue') -and $DoNotAbortNativeToolsInstallationOnFailure) { $showNativeToolsWarning = $true if ((Get-Variable 'DoNotDisplayNativeToolsInstallationWarnings' -ErrorAction 'SilentlyContinue') -and $DoNotDisplayNativeToolsInstallationWarnings) { $showNativeToolsWarning = $false } if ($showNativeToolsWarning) { Write-Warning $errMsg } $toolInstallationFailure = $true } else { # We cannot change this to Write-PipelineTelemetryError because of https://github.com/dotnet/arcade/issues/4482 Write-Host $errMsg exit 1 } } } if ((Get-Variable 'toolInstallationFailure' -ErrorAction 'SilentlyContinue') -and $toolInstallationFailure) { # We cannot change this to Write-PipelineTelemetryError because of https://github.com/dotnet/arcade/issues/4482 Write-Host 'Native tools bootstrap failed' exit 1 } } else { Write-Host 'No native tools defined in global.json' exit 0 } if ($Clean) { exit 0 } if (Test-Path $InstallBin) { Write-Host 'Native tools are available from ' (Convert-Path -Path $InstallBin) Write-Host "##vso[task.prependpath]$(Convert-Path -Path $InstallBin)" return $InstallBin } else { Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message 'Native tools install directory does not exist, installation failed' exit 1 } exit 0 } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message $_ ExitWithExitCode 1 }
-1
dotnet/roslyn
55,436
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
2021-08-05T12:15:00Z
2021-09-15T22:23:32Z
637f10560a5db54783ddd0b9c8ec03eca1992611
fa907a9c608289f85b64ae9b3feadf720c8a5d5a
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210913.4 - **Date Produced**: 9/13/2021 5:12 PM - **Commit**: 4b7c80f398fd3dcea03fdc4e454789b61181d300 - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 6.0.0-beta.21413.4 to 7.0.0-beta.21463.4][1] [1]: https://github.com/dotnet/arcade/compare/9b7027b...4b7c80f [DependencyUpdate]: <> (End) - **Updates to .NET SDKs:** - Updates sdk.version to 6.0.100-rc.1.21430.12 - Updates tools.dotnet to 6.0.100-rc.1.21430.12 [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/templates/post-build/channels/generic-public-channel.yml
parameters: BARBuildId: '' PromoteToChannelIds: '' artifactsPublishingAdditionalParameters: '' dependsOn: - Validate publishInstallersAndChecksums: true symbolPublishingAdditionalParameters: '' stageName: '' channelName: '' channelId: '' transportFeed: '' shippingFeed: '' symbolsFeed: '' # If the channel name is empty, no links will be generated akaMSChannelName: '' stages: - stage: ${{ parameters.stageName }} dependsOn: ${{ parameters.dependsOn }} variables: - template: ../common-variables.yml displayName: ${{ parameters.channelName }} Publishing jobs: - template: ../setup-maestro-vars.yml parameters: BARBuildId: ${{ parameters.BARBuildId }} PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - job: publish_symbols displayName: Symbol Publishing dependsOn: setupMaestroVars condition: contains(dependencies.setupMaestroVars.outputs['setReleaseVars.TargetChannels'], format('[{0}]', ${{ parameters.channelId }} )) variables: - group: DotNet-Symbol-Server-Pats - name: AzDOProjectName value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ] - name: AzDOPipelineId value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ] - name: AzDOBuildId value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ] pool: vmImage: 'windows-2019' steps: - script: echo "##vso[task.logissue type=warning]Going forward, v2 Arcade publishing is no longer supported. Please read https://github.com/dotnet/arcade/blob/main/Documentation/CorePackages/Publishing.md for details, then contact dnceng if you have further questions." displayName: Warn about v2 Arcade Publishing Usage - task: DownloadBuildArtifacts@0 displayName: Download Build Assets continueOnError: true inputs: buildType: specific buildVersionToDownload: specific project: $(AzDOProjectName) pipeline: $(AzDOPipelineId) buildId: $(AzDOBuildId) downloadType: 'specific' itemPattern: | PdbArtifacts/** BlobArtifacts/** downloadPath: '$(Build.ArtifactStagingDirectory)' checkDownloadedFiles: true # This is necessary whenever we want to publish/restore to an AzDO private feed # Since sdk-task.ps1 tries to restore packages we need to do this authentication here # otherwise it'll complain about accessing a private feed. - task: NuGetAuthenticate@0 displayName: 'Authenticate to AzDO Feeds' - task: PowerShell@2 displayName: Enable cross-org publishing inputs: filePath: eng\common\enable-cross-org-publishing.ps1 arguments: -token $(dn-bot-dnceng-artifact-feeds-rw) - task: PowerShell@2 displayName: Publish inputs: filePath: eng\common\sdk-task.ps1 arguments: -task PublishToSymbolServers -restore -msbuildEngine dotnet /p:DotNetSymbolServerTokenMsdl=$(microsoft-symbol-server-pat) /p:DotNetSymbolServerTokenSymWeb=$(symweb-symbol-server-pat) /p:PDBArtifactsDirectory='$(Build.ArtifactStagingDirectory)/PDBArtifacts/' /p:BlobBasePath='$(Build.ArtifactStagingDirectory)/BlobArtifacts/' /p:SymbolPublishingExclusionsFile='$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt' /p:Configuration=Release ${{ parameters.symbolPublishingAdditionalParameters }} - template: ../../steps/publish-logs.yml parameters: StageLabel: '${{ parameters.stageName }}' JobLabel: 'SymbolPublishing' - job: publish_assets displayName: Publish Assets dependsOn: setupMaestroVars timeoutInMinutes: 120 variables: - name: BARBuildId value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.BARBuildId'] ] - name: IsStableBuild value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.IsStableBuild'] ] - name: AzDOProjectName value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ] - name: AzDOPipelineId value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ] - name: AzDOBuildId value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ] - name: ArtifactsCategory value: ${{ coalesce(variables._DotNetArtifactsCategory, '.NETCore') }} condition: contains(dependencies.setupMaestroVars.outputs['setReleaseVars.TargetChannels'], format('[{0}]', ${{ parameters.channelId }} )) pool: vmImage: 'windows-2019' steps: - script: echo "##vso[task.logissue type=warning]Going forward, v2 Arcade publishing is no longer supported. Please read https://github.com/dotnet/arcade/blob/main/Documentation/CorePackages/Publishing.md for details, then contact dnceng if you have further questions." displayName: Warn about v2 Arcade Publishing Usage - task: DownloadBuildArtifacts@0 displayName: Download Build Assets continueOnError: true inputs: buildType: specific buildVersionToDownload: specific project: $(AzDOProjectName) pipeline: $(AzDOPipelineId) buildId: $(AzDOBuildId) downloadType: 'specific' itemPattern: | PackageArtifacts/** BlobArtifacts/** AssetManifests/** downloadPath: '$(Build.ArtifactStagingDirectory)' checkDownloadedFiles: true - task: NuGetToolInstaller@1 displayName: 'Install NuGet.exe' # This is necessary whenever we want to publish/restore to an AzDO private feed - task: NuGetAuthenticate@0 displayName: 'Authenticate to AzDO Feeds' - task: PowerShell@2 displayName: Enable cross-org publishing inputs: filePath: eng\common\enable-cross-org-publishing.ps1 arguments: -token $(dn-bot-dnceng-artifact-feeds-rw) - task: PowerShell@2 displayName: Publish Assets inputs: filePath: eng\common\sdk-task.ps1 arguments: -task PublishArtifactsInManifest -restore -msbuildEngine dotnet /p:PublishingInfraVersion=2 /p:ArtifactsCategory=$(ArtifactsCategory) /p:IsStableBuild=$(IsStableBuild) /p:IsInternalBuild=$(IsInternalBuild) /p:RepositoryName=$(Build.Repository.Name) /p:CommitSha=$(Build.SourceVersion) /p:NugetPath=$(NuGetExeToolPath) /p:AzdoTargetFeedPAT='$(dn-bot-dnceng-universal-packages-rw)' /p:AzureStorageTargetFeedPAT='$(dotnetfeed-storage-access-key-1)' /p:BARBuildId=$(BARBuildId) /p:MaestroApiEndpoint='$(MaestroApiEndPoint)' /p:BuildAssetRegistryToken='$(MaestroApiAccessToken)' /p:ManifestsBasePath='$(Build.ArtifactStagingDirectory)/AssetManifests/' /p:BlobBasePath='$(Build.ArtifactStagingDirectory)/BlobArtifacts/' /p:PackageBasePath='$(Build.ArtifactStagingDirectory)/PackageArtifacts/' /p:Configuration=Release /p:PublishInstallersAndChecksums=${{ parameters.publishInstallersAndChecksums }} /p:InstallersTargetStaticFeed=$(InstallersBlobFeedUrl) /p:InstallersAzureAccountKey=$(dotnetcli-storage-key) /p:ChecksumsTargetStaticFeed=$(ChecksumsBlobFeedUrl) /p:ChecksumsAzureAccountKey=$(dotnetclichecksums-storage-key) /p:AzureDevOpsStaticShippingFeed='${{ parameters.shippingFeed }}' /p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)' /p:AzureDevOpsStaticTransportFeed='${{ parameters.transportFeed }}' /p:AzureDevOpsStaticTransportFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)' /p:AzureDevOpsStaticSymbolsFeed='${{ parameters.symbolsFeed }}' /p:AzureDevOpsStaticSymbolsFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)' /p:LatestLinkShortUrlPrefix=dotnet/'${{ parameters.akaMSChannelName }}' /p:AkaMSClientId=$(akams-client-id) /p:AkaMSClientSecret=$(akams-client-secret) ${{ parameters.artifactsPublishingAdditionalParameters }} - template: ../../steps/publish-logs.yml parameters: StageLabel: '${{ parameters.stageName }}' JobLabel: 'AssetsPublishing' - template: ../../steps/add-build-to-channel.yml parameters: ChannelId: ${{ parameters.channelId }}
parameters: BARBuildId: '' PromoteToChannelIds: '' artifactsPublishingAdditionalParameters: '' dependsOn: - Validate publishInstallersAndChecksums: true symbolPublishingAdditionalParameters: '' stageName: '' channelName: '' channelId: '' transportFeed: '' shippingFeed: '' symbolsFeed: '' # If the channel name is empty, no links will be generated akaMSChannelName: '' stages: - stage: ${{ parameters.stageName }} dependsOn: ${{ parameters.dependsOn }} variables: - template: ../common-variables.yml displayName: ${{ parameters.channelName }} Publishing jobs: - template: ../setup-maestro-vars.yml parameters: BARBuildId: ${{ parameters.BARBuildId }} PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - job: publish_symbols displayName: Symbol Publishing dependsOn: setupMaestroVars condition: contains(dependencies.setupMaestroVars.outputs['setReleaseVars.TargetChannels'], format('[{0}]', ${{ parameters.channelId }} )) variables: - group: DotNet-Symbol-Server-Pats - name: AzDOProjectName value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ] - name: AzDOPipelineId value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ] - name: AzDOBuildId value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ] pool: vmImage: 'windows-2019' steps: - script: echo "##vso[task.logissue type=warning]Going forward, v2 Arcade publishing is no longer supported. Please read https://github.com/dotnet/arcade/blob/main/Documentation/CorePackages/Publishing.md for details, then contact dnceng if you have further questions." displayName: Warn about v2 Arcade Publishing Usage - task: DownloadBuildArtifacts@0 displayName: Download Build Assets continueOnError: true inputs: buildType: specific buildVersionToDownload: specific project: $(AzDOProjectName) pipeline: $(AzDOPipelineId) buildId: $(AzDOBuildId) downloadType: 'specific' itemPattern: | PdbArtifacts/** BlobArtifacts/** downloadPath: '$(Build.ArtifactStagingDirectory)' checkDownloadedFiles: true # This is necessary whenever we want to publish/restore to an AzDO private feed # Since sdk-task.ps1 tries to restore packages we need to do this authentication here # otherwise it'll complain about accessing a private feed. - task: NuGetAuthenticate@0 displayName: 'Authenticate to AzDO Feeds' - task: PowerShell@2 displayName: Enable cross-org publishing inputs: filePath: eng\common\enable-cross-org-publishing.ps1 arguments: -token $(dn-bot-dnceng-artifact-feeds-rw) - task: PowerShell@2 displayName: Publish inputs: filePath: eng\common\sdk-task.ps1 arguments: -task PublishToSymbolServers -restore -msbuildEngine dotnet /p:DotNetSymbolServerTokenMsdl=$(microsoft-symbol-server-pat) /p:DotNetSymbolServerTokenSymWeb=$(symweb-symbol-server-pat) /p:PDBArtifactsDirectory='$(Build.ArtifactStagingDirectory)/PDBArtifacts/' /p:BlobBasePath='$(Build.ArtifactStagingDirectory)/BlobArtifacts/' /p:SymbolPublishingExclusionsFile='$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt' /p:Configuration=Release ${{ parameters.symbolPublishingAdditionalParameters }} - template: ../../steps/publish-logs.yml parameters: StageLabel: '${{ parameters.stageName }}' JobLabel: 'SymbolPublishing' - job: publish_assets displayName: Publish Assets dependsOn: setupMaestroVars timeoutInMinutes: 120 variables: - name: BARBuildId value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.BARBuildId'] ] - name: IsStableBuild value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.IsStableBuild'] ] - name: AzDOProjectName value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ] - name: AzDOPipelineId value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ] - name: AzDOBuildId value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ] - name: ArtifactsCategory value: ${{ coalesce(variables._DotNetArtifactsCategory, '.NETCore') }} condition: contains(dependencies.setupMaestroVars.outputs['setReleaseVars.TargetChannels'], format('[{0}]', ${{ parameters.channelId }} )) pool: vmImage: 'windows-2019' steps: - script: echo "##vso[task.logissue type=warning]Going forward, v2 Arcade publishing is no longer supported. Please read https://github.com/dotnet/arcade/blob/main/Documentation/CorePackages/Publishing.md for details, then contact dnceng if you have further questions." displayName: Warn about v2 Arcade Publishing Usage - task: DownloadBuildArtifacts@0 displayName: Download Build Assets continueOnError: true inputs: buildType: specific buildVersionToDownload: specific project: $(AzDOProjectName) pipeline: $(AzDOPipelineId) buildId: $(AzDOBuildId) downloadType: 'specific' itemPattern: | PackageArtifacts/** BlobArtifacts/** AssetManifests/** downloadPath: '$(Build.ArtifactStagingDirectory)' checkDownloadedFiles: true - task: NuGetToolInstaller@1 displayName: 'Install NuGet.exe' # This is necessary whenever we want to publish/restore to an AzDO private feed - task: NuGetAuthenticate@0 displayName: 'Authenticate to AzDO Feeds' - task: PowerShell@2 displayName: Enable cross-org publishing inputs: filePath: eng\common\enable-cross-org-publishing.ps1 arguments: -token $(dn-bot-dnceng-artifact-feeds-rw) - task: PowerShell@2 displayName: Publish Assets inputs: filePath: eng\common\sdk-task.ps1 arguments: -task PublishArtifactsInManifest -restore -msbuildEngine dotnet /p:PublishingInfraVersion=2 /p:ArtifactsCategory=$(ArtifactsCategory) /p:IsStableBuild=$(IsStableBuild) /p:IsInternalBuild=$(IsInternalBuild) /p:RepositoryName=$(Build.Repository.Name) /p:CommitSha=$(Build.SourceVersion) /p:NugetPath=$(NuGetExeToolPath) /p:AzdoTargetFeedPAT='$(dn-bot-dnceng-universal-packages-rw)' /p:AzureStorageTargetFeedPAT='$(dotnetfeed-storage-access-key-1)' /p:BARBuildId=$(BARBuildId) /p:MaestroApiEndpoint='$(MaestroApiEndPoint)' /p:BuildAssetRegistryToken='$(MaestroApiAccessToken)' /p:ManifestsBasePath='$(Build.ArtifactStagingDirectory)/AssetManifests/' /p:BlobBasePath='$(Build.ArtifactStagingDirectory)/BlobArtifacts/' /p:PackageBasePath='$(Build.ArtifactStagingDirectory)/PackageArtifacts/' /p:Configuration=Release /p:PublishInstallersAndChecksums=${{ parameters.publishInstallersAndChecksums }} /p:InstallersTargetStaticFeed=$(InstallersBlobFeedUrl) /p:InstallersAzureAccountKey=$(dotnetcli-storage-key) /p:ChecksumsTargetStaticFeed=$(ChecksumsBlobFeedUrl) /p:ChecksumsAzureAccountKey=$(dotnetclichecksums-storage-key) /p:AzureDevOpsStaticShippingFeed='${{ parameters.shippingFeed }}' /p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)' /p:AzureDevOpsStaticTransportFeed='${{ parameters.transportFeed }}' /p:AzureDevOpsStaticTransportFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)' /p:AzureDevOpsStaticSymbolsFeed='${{ parameters.symbolsFeed }}' /p:AzureDevOpsStaticSymbolsFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)' /p:LatestLinkShortUrlPrefix=dotnet/'${{ parameters.akaMSChannelName }}' /p:AkaMSClientId=$(akams-client-id) /p:AkaMSClientSecret=$(akams-client-secret) ${{ parameters.artifactsPublishingAdditionalParameters }} - template: ../../steps/publish-logs.yml parameters: StageLabel: '${{ parameters.stageName }}' JobLabel: 'AssetsPublishing' - template: ../../steps/add-build-to-channel.yml parameters: ChannelId: ${{ parameters.channelId }}
-1