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,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Scripting/Core/Hosting/AssemblyLoader/MetadataShadowCopy.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; namespace Microsoft.CodeAnalysis.Scripting.Hosting { /// <summary> /// Represents a shadow copy of an assembly or a standalone module. /// </summary> public sealed class MetadataShadowCopy { /// <summary> /// Assembly manifest module copy or a standalone module copy. /// </summary> public FileShadowCopy PrimaryModule { get; } /// <summary> /// Documentation file copy or null if there is none. /// </summary> /// <remarks> /// Documentation files are currently only supported for manifest modules, not modules included in an assembly. /// </remarks> public FileShadowCopy DocumentationFile { get; } // this instance doesn't own the image public Metadata Metadata { get; } internal MetadataShadowCopy(FileShadowCopy primaryModule, FileShadowCopy documentationFileOpt, Metadata metadataCopy) { Debug.Assert(primaryModule != null); Debug.Assert(metadataCopy != null); ////Debug.Assert(!metadataCopy.IsImageOwner); property is now internal PrimaryModule = primaryModule; DocumentationFile = documentationFileOpt; Metadata = metadataCopy; } // keep this internal so that users can't delete files that the provider manages internal void DisposeFileHandles() { PrimaryModule.DisposeFileStream(); DocumentationFile?.DisposeFileStream(); } } }
// 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; namespace Microsoft.CodeAnalysis.Scripting.Hosting { /// <summary> /// Represents a shadow copy of an assembly or a standalone module. /// </summary> public sealed class MetadataShadowCopy { /// <summary> /// Assembly manifest module copy or a standalone module copy. /// </summary> public FileShadowCopy PrimaryModule { get; } /// <summary> /// Documentation file copy or null if there is none. /// </summary> /// <remarks> /// Documentation files are currently only supported for manifest modules, not modules included in an assembly. /// </remarks> public FileShadowCopy DocumentationFile { get; } // this instance doesn't own the image public Metadata Metadata { get; } internal MetadataShadowCopy(FileShadowCopy primaryModule, FileShadowCopy documentationFileOpt, Metadata metadataCopy) { Debug.Assert(primaryModule != null); Debug.Assert(metadataCopy != null); ////Debug.Assert(!metadataCopy.IsImageOwner); property is now internal PrimaryModule = primaryModule; DocumentationFile = documentationFileOpt; Metadata = metadataCopy; } // keep this internal so that users can't delete files that the provider manages internal void DisposeFileHandles() { PrimaryModule.DisposeFileStream(); DocumentationFile?.DisposeFileStream(); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/CSharp/Portable/Binder/Binder_Await.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.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts an AwaitExpressionSyntax into a BoundExpression /// </summary> internal partial class Binder { private BoundExpression BindAwait(AwaitExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression expression = BindRValueWithoutTargetType(node.Expression, diagnostics); return BindAwait(expression, node, diagnostics); } private BoundAwaitExpression BindAwait(BoundExpression expression, SyntaxNode node, BindingDiagnosticBag diagnostics) { bool hasErrors = false; var placeholder = new BoundAwaitableValuePlaceholder(expression.Syntax, GetValEscape(expression, LocalScopeDepth), expression.Type); ReportBadAwaitDiagnostics(node, node.Location, diagnostics, ref hasErrors); var info = BindAwaitInfo(placeholder, node, diagnostics, ref hasErrors, expressionOpt: expression); // Spec 7.7.7.2: // The expression await t is classified the same way as the expression (t).GetAwaiter().GetResult(). Thus, // if the return type of GetResult is void, the await-expression is classified as nothing. If it has a // non-void return type T, the await-expression is classified as a value of type T. TypeSymbol awaitExpressionType = info.GetResult?.ReturnType ?? (hasErrors ? CreateErrorType() : Compilation.DynamicType); return new BoundAwaitExpression(node, expression, info, awaitExpressionType, hasErrors); } internal void ReportBadAwaitDiagnostics(SyntaxNode node, Location location, BindingDiagnosticBag diagnostics, ref bool hasErrors) { hasErrors |= ReportBadAwaitWithoutAsync(location, diagnostics); hasErrors |= ReportBadAwaitContext(node, location, diagnostics); } internal BoundAwaitableInfo BindAwaitInfo(BoundAwaitableValuePlaceholder placeholder, SyntaxNode node, BindingDiagnosticBag diagnostics, ref bool hasErrors, BoundExpression? expressionOpt = null) { bool hasGetAwaitableErrors = !GetAwaitableExpressionInfo( expressionOpt ?? placeholder, placeholder, out bool isDynamic, out BoundExpression? getAwaiter, out PropertySymbol? isCompleted, out MethodSymbol? getResult, getAwaiterGetResultCall: out _, node, diagnostics); hasErrors |= hasGetAwaitableErrors; return new BoundAwaitableInfo(node, placeholder, isDynamic: isDynamic, getAwaiter, isCompleted, getResult, hasErrors: hasGetAwaitableErrors) { WasCompilerGenerated = true }; } /// <summary> /// Return true iff an await with this subexpression would be legal where the expression appears. /// </summary> private bool CouldBeAwaited(BoundExpression expression) { // If the expression doesn't have a type, just bail out now. Also, // the dynamic type is always awaitable in an async method and // could generate a lot of noise if we warned on it. Finally, we only want // to warn on method calls, not other kinds of expressions. if (expression.Kind != BoundKind.Call) { return false; } var type = expression.Type; if ((type is null) || type.IsDynamic() || (type.IsVoidType())) { return false; } var call = (BoundCall)expression; // First check if the target method is async. if ((object)call.Method != null && call.Method.IsAsync) { return true; } // Then check if the method call returns a WinRT async type. if (ImplementsWinRTAsyncInterface(call.Type)) { return true; } // Finally, if we're in an async method, and the expression could be awaited, report that it is instead discarded. var containingMethod = this.ContainingMemberOrLambda as MethodSymbol; if (containingMethod is null || !containingMethod.IsAsync) { return false; } if (ContextForbidsAwait) { return false; } var boundAwait = BindAwait(expression, expression.Syntax, BindingDiagnosticBag.Discarded); return !boundAwait.HasAnyErrors; } /// <summary> /// Assuming we are in an async method, return true if we're in a context where await would be illegal. /// Specifically, return true if we're in a lock or catch filter. /// </summary> private bool ContextForbidsAwait { get { return this.Flags.Includes(BinderFlags.InCatchFilter) || this.Flags.Includes(BinderFlags.InLockBody); } } /// <summary> /// Reports an error if the await expression did not occur in an async context. /// </summary> /// <returns>True if the expression contains errors.</returns> [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "'await without async' refers to the error scenario.")] private bool ReportBadAwaitWithoutAsync(Location location, BindingDiagnosticBag diagnostics) { DiagnosticInfo? info = null; var containingMemberOrLambda = this.ContainingMemberOrLambda; if (containingMemberOrLambda is object) { switch (containingMemberOrLambda.Kind) { case SymbolKind.Field: if (containingMemberOrLambda.ContainingType.IsScriptClass) { if (((FieldSymbol)containingMemberOrLambda).IsStatic) { info = new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitInStaticVariableInitializer); } else { return false; } } break; case SymbolKind.Method: var method = (MethodSymbol)containingMemberOrLambda; if (method.IsAsync) { return false; } if (method.MethodKind == MethodKind.AnonymousFunction) { info = method.IsImplicitlyDeclared ? // The await expression occurred in a query expression: new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitInQuery) : new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitWithoutAsyncLambda, ((LambdaSymbol)method).MessageID.Localize()); } else { info = method.ReturnsVoid ? new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod) : new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitWithoutAsyncMethod, method.ReturnType); } break; } } if (info == null) { info = new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitWithoutAsync); } Error(diagnostics, info, location); return true; } /// <summary> /// Report diagnostics if the await expression occurs in a context where it is not allowed. /// </summary> /// <returns>True if errors were found.</returns> private bool ReportBadAwaitContext(SyntaxNode node, Location location, BindingDiagnosticBag diagnostics) { if (this.InUnsafeRegion && !this.Flags.Includes(BinderFlags.AllowAwaitInUnsafeContext)) { Error(diagnostics, ErrorCode.ERR_AwaitInUnsafeContext, location); return true; } else if (this.Flags.Includes(BinderFlags.InLockBody)) { Error(diagnostics, ErrorCode.ERR_BadAwaitInLock, location); return true; } else if (this.Flags.Includes(BinderFlags.InCatchFilter)) { Error(diagnostics, ErrorCode.ERR_BadAwaitInCatchFilter, location); return true; } else if (this.Flags.Includes(BinderFlags.InFinallyBlock) && (node.SyntaxTree as CSharpSyntaxTree)?.Options?.IsFeatureEnabled(MessageID.IDS_AwaitInCatchAndFinally) == false) { Error(diagnostics, ErrorCode.ERR_BadAwaitInFinally, location); return true; } else if (this.Flags.Includes(BinderFlags.InCatchBlock) && (node.SyntaxTree as CSharpSyntaxTree)?.Options?.IsFeatureEnabled(MessageID.IDS_AwaitInCatchAndFinally) == false) { Error(diagnostics, ErrorCode.ERR_BadAwaitInCatch, location); return true; } else { return false; } } /// <summary> /// Finds and validates the required members of an awaitable expression, as described in spec 7.7.7.1. /// </summary> /// <returns>True if the expression is awaitable; false otherwise.</returns> internal bool GetAwaitableExpressionInfo( BoundExpression expression, out BoundExpression? getAwaiterGetResultCall, SyntaxNode node, BindingDiagnosticBag diagnostics) { return GetAwaitableExpressionInfo(expression, expression, out _, out _, out _, out _, out getAwaiterGetResultCall, node, diagnostics); } private bool GetAwaitableExpressionInfo( BoundExpression expression, BoundExpression getAwaiterArgument, out bool isDynamic, out BoundExpression? getAwaiter, out PropertySymbol? isCompleted, out MethodSymbol? getResult, out BoundExpression? getAwaiterGetResultCall, SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(TypeSymbol.Equals(expression.Type, getAwaiterArgument.Type, TypeCompareKind.ConsiderEverything)); isDynamic = false; getAwaiter = null; isCompleted = null; getResult = null; getAwaiterGetResultCall = null; if (!ValidateAwaitedExpression(expression, node, diagnostics)) { return false; } if (expression.HasDynamicType()) { isDynamic = true; return true; } if (!GetGetAwaiterMethod(getAwaiterArgument, node, diagnostics, out getAwaiter)) { return false; } TypeSymbol awaiterType = getAwaiter.Type!; return GetIsCompletedProperty(awaiterType, node, expression.Type!, diagnostics, out isCompleted) && AwaiterImplementsINotifyCompletion(awaiterType, node, diagnostics) && GetGetResultMethod(getAwaiter, node, expression.Type!, diagnostics, out getResult, out getAwaiterGetResultCall); } /// <summary> /// Validates the awaited expression, returning true if no errors are found. /// </summary> private static bool ValidateAwaitedExpression(BoundExpression expression, SyntaxNode node, BindingDiagnosticBag diagnostics) { if (expression.HasAnyErrors) { // The appropriate diagnostics have already been reported. return false; } if (expression.Type is null) { Error(diagnostics, ErrorCode.ERR_BadAwaitArgIntrinsic, node, expression.Display); return false; } return true; } /// <summary> /// Finds the GetAwaiter method of an awaitable expression. /// </summary> /// <remarks> /// Spec 7.7.7.1: /// An awaitable expression t has an accessible instance or extension method called GetAwaiter with no /// parameters and no type parameters, and a return type A that meets the additional requirements for an /// Awaiter. /// NOTE: this is an error in the spec. An extension method of the form /// Awaiter&lt;T&gt; GetAwaiter&lt;T&gt;(this Task&lt;T&gt;) may be used. /// </remarks> private bool GetGetAwaiterMethod(BoundExpression expression, SyntaxNode node, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundExpression? getAwaiterCall) { RoslynDebug.Assert(expression.Type is object); if (expression.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_BadAwaitArgVoidCall, node); getAwaiterCall = null; return false; } getAwaiterCall = MakeInvocationExpression(node, expression, WellKnownMemberNames.GetAwaiter, ImmutableArray<BoundExpression>.Empty, diagnostics); if (getAwaiterCall.HasAnyErrors) // && !expression.HasAnyErrors? { getAwaiterCall = null; return false; } if (getAwaiterCall.Kind != BoundKind.Call) { Error(diagnostics, ErrorCode.ERR_BadAwaitArg, node, expression.Type); getAwaiterCall = null; return false; } var getAwaiterMethod = ((BoundCall)getAwaiterCall).Method; if (getAwaiterMethod is ErrorMethodSymbol || HasOptionalOrVariableParameters(getAwaiterMethod) || // We might have been able to resolve a GetAwaiter overload with optional parameters, so check for that here getAwaiterMethod.ReturnsVoid) // If GetAwaiter returns void, don't bother checking that it returns an Awaiter. { Error(diagnostics, ErrorCode.ERR_BadAwaitArg, node, expression.Type); getAwaiterCall = null; return false; } return true; } /// <summary> /// Finds the IsCompleted property of an Awaiter type. /// </summary> /// <remarks> /// Spec 7.7.7.1: /// An Awaiter A has an accessible, readable instance property IsCompleted of type bool. /// </remarks> private bool GetIsCompletedProperty(TypeSymbol awaiterType, SyntaxNode node, TypeSymbol awaitedExpressionType, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out PropertySymbol? isCompletedProperty) { var receiver = new BoundLiteral(node, ConstantValue.Null, awaiterType); var name = WellKnownMemberNames.IsCompleted; var qualified = BindInstanceMemberAccess(node, node, receiver, name, 0, default(SeparatedSyntaxList<TypeSyntax>), default(ImmutableArray<TypeWithAnnotations>), invoked: false, indexed: false, diagnostics); if (qualified.HasAnyErrors) { isCompletedProperty = null; return false; } if (qualified.Kind != BoundKind.PropertyAccess) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, node, awaiterType, WellKnownMemberNames.IsCompleted); isCompletedProperty = null; return false; } isCompletedProperty = ((BoundPropertyAccess)qualified).PropertySymbol; if (isCompletedProperty.IsWriteOnly) { Error(diagnostics, ErrorCode.ERR_PropertyLacksGet, node, isCompletedProperty); isCompletedProperty = null; return false; } if (isCompletedProperty.Type.SpecialType != SpecialType.System_Boolean) { Error(diagnostics, ErrorCode.ERR_BadAwaiterPattern, node, awaiterType, awaitedExpressionType); isCompletedProperty = null; return false; } return true; } /// <summary> /// Checks that the Awaiter implements System.Runtime.CompilerServices.INotifyCompletion. /// </summary> /// <remarks> /// Spec 7.7.7.1: /// An Awaiter A implements the interface System.Runtime.CompilerServices.INotifyCompletion. /// </remarks> private bool AwaiterImplementsINotifyCompletion(TypeSymbol awaiterType, SyntaxNode node, BindingDiagnosticBag diagnostics) { var INotifyCompletion = GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_INotifyCompletion, diagnostics, node); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyImplicitConversionFromType(awaiterType, INotifyCompletion, ref useSiteInfo); if (!conversion.IsImplicit) { diagnostics.Add(node, useSiteInfo); Error(diagnostics, ErrorCode.ERR_DoesntImplementAwaitInterface, node, awaiterType, INotifyCompletion); return false; } Debug.Assert(conversion.IsValid); return true; } /// <summary> /// Finds the GetResult method of an Awaiter type. /// </summary> /// <remarks> /// Spec 7.7.7.1: /// An Awaiter A has an accessible instance method GetResult with no parameters and no type parameters. /// </remarks> private bool GetGetResultMethod(BoundExpression awaiterExpression, SyntaxNode node, TypeSymbol awaitedExpressionType, BindingDiagnosticBag diagnostics, out MethodSymbol? getResultMethod, [NotNullWhen(true)] out BoundExpression? getAwaiterGetResultCall) { var awaiterType = awaiterExpression.Type; getAwaiterGetResultCall = MakeInvocationExpression(node, awaiterExpression, WellKnownMemberNames.GetResult, ImmutableArray<BoundExpression>.Empty, diagnostics); if (getAwaiterGetResultCall.HasAnyErrors) { getResultMethod = null; getAwaiterGetResultCall = null; return false; } RoslynDebug.Assert(awaiterType is object); if (getAwaiterGetResultCall.Kind != BoundKind.Call) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, node, awaiterType, WellKnownMemberNames.GetResult); getResultMethod = null; getAwaiterGetResultCall = null; return false; } getResultMethod = ((BoundCall)getAwaiterGetResultCall).Method; if (getResultMethod.IsExtensionMethod) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, node, awaiterType, WellKnownMemberNames.GetResult); getResultMethod = null; getAwaiterGetResultCall = null; return false; } if (HasOptionalOrVariableParameters(getResultMethod) || getResultMethod.IsConditional) { Error(diagnostics, ErrorCode.ERR_BadAwaiterPattern, node, awaiterType, awaitedExpressionType); getResultMethod = null; getAwaiterGetResultCall = null; return false; } // The lack of a GetResult method will be reported by ValidateGetResult(). return true; } private static bool HasOptionalOrVariableParameters(MethodSymbol method) { RoslynDebug.Assert(method != null); if (method.ParameterCount != 0) { var parameter = method.Parameters[method.ParameterCount - 1]; return parameter.IsOptional || parameter.IsParams; } return false; } } }
// 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.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts an AwaitExpressionSyntax into a BoundExpression /// </summary> internal partial class Binder { private BoundExpression BindAwait(AwaitExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression expression = BindRValueWithoutTargetType(node.Expression, diagnostics); return BindAwait(expression, node, diagnostics); } private BoundAwaitExpression BindAwait(BoundExpression expression, SyntaxNode node, BindingDiagnosticBag diagnostics) { bool hasErrors = false; var placeholder = new BoundAwaitableValuePlaceholder(expression.Syntax, GetValEscape(expression, LocalScopeDepth), expression.Type); ReportBadAwaitDiagnostics(node, node.Location, diagnostics, ref hasErrors); var info = BindAwaitInfo(placeholder, node, diagnostics, ref hasErrors, expressionOpt: expression); // Spec 7.7.7.2: // The expression await t is classified the same way as the expression (t).GetAwaiter().GetResult(). Thus, // if the return type of GetResult is void, the await-expression is classified as nothing. If it has a // non-void return type T, the await-expression is classified as a value of type T. TypeSymbol awaitExpressionType = info.GetResult?.ReturnType ?? (hasErrors ? CreateErrorType() : Compilation.DynamicType); return new BoundAwaitExpression(node, expression, info, awaitExpressionType, hasErrors); } internal void ReportBadAwaitDiagnostics(SyntaxNode node, Location location, BindingDiagnosticBag diagnostics, ref bool hasErrors) { hasErrors |= ReportBadAwaitWithoutAsync(location, diagnostics); hasErrors |= ReportBadAwaitContext(node, location, diagnostics); } internal BoundAwaitableInfo BindAwaitInfo(BoundAwaitableValuePlaceholder placeholder, SyntaxNode node, BindingDiagnosticBag diagnostics, ref bool hasErrors, BoundExpression? expressionOpt = null) { bool hasGetAwaitableErrors = !GetAwaitableExpressionInfo( expressionOpt ?? placeholder, placeholder, out bool isDynamic, out BoundExpression? getAwaiter, out PropertySymbol? isCompleted, out MethodSymbol? getResult, getAwaiterGetResultCall: out _, node, diagnostics); hasErrors |= hasGetAwaitableErrors; return new BoundAwaitableInfo(node, placeholder, isDynamic: isDynamic, getAwaiter, isCompleted, getResult, hasErrors: hasGetAwaitableErrors) { WasCompilerGenerated = true }; } /// <summary> /// Return true iff an await with this subexpression would be legal where the expression appears. /// </summary> private bool CouldBeAwaited(BoundExpression expression) { // If the expression doesn't have a type, just bail out now. Also, // the dynamic type is always awaitable in an async method and // could generate a lot of noise if we warned on it. Finally, we only want // to warn on method calls, not other kinds of expressions. if (expression.Kind != BoundKind.Call) { return false; } var type = expression.Type; if ((type is null) || type.IsDynamic() || (type.IsVoidType())) { return false; } var call = (BoundCall)expression; // First check if the target method is async. if ((object)call.Method != null && call.Method.IsAsync) { return true; } // Then check if the method call returns a WinRT async type. if (ImplementsWinRTAsyncInterface(call.Type)) { return true; } // Finally, if we're in an async method, and the expression could be awaited, report that it is instead discarded. var containingMethod = this.ContainingMemberOrLambda as MethodSymbol; if (containingMethod is null || !containingMethod.IsAsync) { return false; } if (ContextForbidsAwait) { return false; } var boundAwait = BindAwait(expression, expression.Syntax, BindingDiagnosticBag.Discarded); return !boundAwait.HasAnyErrors; } /// <summary> /// Assuming we are in an async method, return true if we're in a context where await would be illegal. /// Specifically, return true if we're in a lock or catch filter. /// </summary> private bool ContextForbidsAwait { get { return this.Flags.Includes(BinderFlags.InCatchFilter) || this.Flags.Includes(BinderFlags.InLockBody); } } /// <summary> /// Reports an error if the await expression did not occur in an async context. /// </summary> /// <returns>True if the expression contains errors.</returns> [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "'await without async' refers to the error scenario.")] private bool ReportBadAwaitWithoutAsync(Location location, BindingDiagnosticBag diagnostics) { DiagnosticInfo? info = null; var containingMemberOrLambda = this.ContainingMemberOrLambda; if (containingMemberOrLambda is object) { switch (containingMemberOrLambda.Kind) { case SymbolKind.Field: if (containingMemberOrLambda.ContainingType.IsScriptClass) { if (((FieldSymbol)containingMemberOrLambda).IsStatic) { info = new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitInStaticVariableInitializer); } else { return false; } } break; case SymbolKind.Method: var method = (MethodSymbol)containingMemberOrLambda; if (method.IsAsync) { return false; } if (method.MethodKind == MethodKind.AnonymousFunction) { info = method.IsImplicitlyDeclared ? // The await expression occurred in a query expression: new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitInQuery) : new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitWithoutAsyncLambda, ((LambdaSymbol)method).MessageID.Localize()); } else { info = method.ReturnsVoid ? new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod) : new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitWithoutAsyncMethod, method.ReturnType); } break; } } if (info == null) { info = new CSDiagnosticInfo(ErrorCode.ERR_BadAwaitWithoutAsync); } Error(diagnostics, info, location); return true; } /// <summary> /// Report diagnostics if the await expression occurs in a context where it is not allowed. /// </summary> /// <returns>True if errors were found.</returns> private bool ReportBadAwaitContext(SyntaxNode node, Location location, BindingDiagnosticBag diagnostics) { if (this.InUnsafeRegion && !this.Flags.Includes(BinderFlags.AllowAwaitInUnsafeContext)) { Error(diagnostics, ErrorCode.ERR_AwaitInUnsafeContext, location); return true; } else if (this.Flags.Includes(BinderFlags.InLockBody)) { Error(diagnostics, ErrorCode.ERR_BadAwaitInLock, location); return true; } else if (this.Flags.Includes(BinderFlags.InCatchFilter)) { Error(diagnostics, ErrorCode.ERR_BadAwaitInCatchFilter, location); return true; } else if (this.Flags.Includes(BinderFlags.InFinallyBlock) && (node.SyntaxTree as CSharpSyntaxTree)?.Options?.IsFeatureEnabled(MessageID.IDS_AwaitInCatchAndFinally) == false) { Error(diagnostics, ErrorCode.ERR_BadAwaitInFinally, location); return true; } else if (this.Flags.Includes(BinderFlags.InCatchBlock) && (node.SyntaxTree as CSharpSyntaxTree)?.Options?.IsFeatureEnabled(MessageID.IDS_AwaitInCatchAndFinally) == false) { Error(diagnostics, ErrorCode.ERR_BadAwaitInCatch, location); return true; } else { return false; } } /// <summary> /// Finds and validates the required members of an awaitable expression, as described in spec 7.7.7.1. /// </summary> /// <returns>True if the expression is awaitable; false otherwise.</returns> internal bool GetAwaitableExpressionInfo( BoundExpression expression, out BoundExpression? getAwaiterGetResultCall, SyntaxNode node, BindingDiagnosticBag diagnostics) { return GetAwaitableExpressionInfo(expression, expression, out _, out _, out _, out _, out getAwaiterGetResultCall, node, diagnostics); } private bool GetAwaitableExpressionInfo( BoundExpression expression, BoundExpression getAwaiterArgument, out bool isDynamic, out BoundExpression? getAwaiter, out PropertySymbol? isCompleted, out MethodSymbol? getResult, out BoundExpression? getAwaiterGetResultCall, SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(TypeSymbol.Equals(expression.Type, getAwaiterArgument.Type, TypeCompareKind.ConsiderEverything)); isDynamic = false; getAwaiter = null; isCompleted = null; getResult = null; getAwaiterGetResultCall = null; if (!ValidateAwaitedExpression(expression, node, diagnostics)) { return false; } if (expression.HasDynamicType()) { isDynamic = true; return true; } if (!GetGetAwaiterMethod(getAwaiterArgument, node, diagnostics, out getAwaiter)) { return false; } TypeSymbol awaiterType = getAwaiter.Type!; return GetIsCompletedProperty(awaiterType, node, expression.Type!, diagnostics, out isCompleted) && AwaiterImplementsINotifyCompletion(awaiterType, node, diagnostics) && GetGetResultMethod(getAwaiter, node, expression.Type!, diagnostics, out getResult, out getAwaiterGetResultCall); } /// <summary> /// Validates the awaited expression, returning true if no errors are found. /// </summary> private static bool ValidateAwaitedExpression(BoundExpression expression, SyntaxNode node, BindingDiagnosticBag diagnostics) { if (expression.HasAnyErrors) { // The appropriate diagnostics have already been reported. return false; } if (expression.Type is null) { Error(diagnostics, ErrorCode.ERR_BadAwaitArgIntrinsic, node, expression.Display); return false; } return true; } /// <summary> /// Finds the GetAwaiter method of an awaitable expression. /// </summary> /// <remarks> /// Spec 7.7.7.1: /// An awaitable expression t has an accessible instance or extension method called GetAwaiter with no /// parameters and no type parameters, and a return type A that meets the additional requirements for an /// Awaiter. /// NOTE: this is an error in the spec. An extension method of the form /// Awaiter&lt;T&gt; GetAwaiter&lt;T&gt;(this Task&lt;T&gt;) may be used. /// </remarks> private bool GetGetAwaiterMethod(BoundExpression expression, SyntaxNode node, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundExpression? getAwaiterCall) { RoslynDebug.Assert(expression.Type is object); if (expression.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_BadAwaitArgVoidCall, node); getAwaiterCall = null; return false; } getAwaiterCall = MakeInvocationExpression(node, expression, WellKnownMemberNames.GetAwaiter, ImmutableArray<BoundExpression>.Empty, diagnostics); if (getAwaiterCall.HasAnyErrors) // && !expression.HasAnyErrors? { getAwaiterCall = null; return false; } if (getAwaiterCall.Kind != BoundKind.Call) { Error(diagnostics, ErrorCode.ERR_BadAwaitArg, node, expression.Type); getAwaiterCall = null; return false; } var getAwaiterMethod = ((BoundCall)getAwaiterCall).Method; if (getAwaiterMethod is ErrorMethodSymbol || HasOptionalOrVariableParameters(getAwaiterMethod) || // We might have been able to resolve a GetAwaiter overload with optional parameters, so check for that here getAwaiterMethod.ReturnsVoid) // If GetAwaiter returns void, don't bother checking that it returns an Awaiter. { Error(diagnostics, ErrorCode.ERR_BadAwaitArg, node, expression.Type); getAwaiterCall = null; return false; } return true; } /// <summary> /// Finds the IsCompleted property of an Awaiter type. /// </summary> /// <remarks> /// Spec 7.7.7.1: /// An Awaiter A has an accessible, readable instance property IsCompleted of type bool. /// </remarks> private bool GetIsCompletedProperty(TypeSymbol awaiterType, SyntaxNode node, TypeSymbol awaitedExpressionType, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out PropertySymbol? isCompletedProperty) { var receiver = new BoundLiteral(node, ConstantValue.Null, awaiterType); var name = WellKnownMemberNames.IsCompleted; var qualified = BindInstanceMemberAccess(node, node, receiver, name, 0, default(SeparatedSyntaxList<TypeSyntax>), default(ImmutableArray<TypeWithAnnotations>), invoked: false, indexed: false, diagnostics); if (qualified.HasAnyErrors) { isCompletedProperty = null; return false; } if (qualified.Kind != BoundKind.PropertyAccess) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, node, awaiterType, WellKnownMemberNames.IsCompleted); isCompletedProperty = null; return false; } isCompletedProperty = ((BoundPropertyAccess)qualified).PropertySymbol; if (isCompletedProperty.IsWriteOnly) { Error(diagnostics, ErrorCode.ERR_PropertyLacksGet, node, isCompletedProperty); isCompletedProperty = null; return false; } if (isCompletedProperty.Type.SpecialType != SpecialType.System_Boolean) { Error(diagnostics, ErrorCode.ERR_BadAwaiterPattern, node, awaiterType, awaitedExpressionType); isCompletedProperty = null; return false; } return true; } /// <summary> /// Checks that the Awaiter implements System.Runtime.CompilerServices.INotifyCompletion. /// </summary> /// <remarks> /// Spec 7.7.7.1: /// An Awaiter A implements the interface System.Runtime.CompilerServices.INotifyCompletion. /// </remarks> private bool AwaiterImplementsINotifyCompletion(TypeSymbol awaiterType, SyntaxNode node, BindingDiagnosticBag diagnostics) { var INotifyCompletion = GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_INotifyCompletion, diagnostics, node); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyImplicitConversionFromType(awaiterType, INotifyCompletion, ref useSiteInfo); if (!conversion.IsImplicit) { diagnostics.Add(node, useSiteInfo); Error(diagnostics, ErrorCode.ERR_DoesntImplementAwaitInterface, node, awaiterType, INotifyCompletion); return false; } Debug.Assert(conversion.IsValid); return true; } /// <summary> /// Finds the GetResult method of an Awaiter type. /// </summary> /// <remarks> /// Spec 7.7.7.1: /// An Awaiter A has an accessible instance method GetResult with no parameters and no type parameters. /// </remarks> private bool GetGetResultMethod(BoundExpression awaiterExpression, SyntaxNode node, TypeSymbol awaitedExpressionType, BindingDiagnosticBag diagnostics, out MethodSymbol? getResultMethod, [NotNullWhen(true)] out BoundExpression? getAwaiterGetResultCall) { var awaiterType = awaiterExpression.Type; getAwaiterGetResultCall = MakeInvocationExpression(node, awaiterExpression, WellKnownMemberNames.GetResult, ImmutableArray<BoundExpression>.Empty, diagnostics); if (getAwaiterGetResultCall.HasAnyErrors) { getResultMethod = null; getAwaiterGetResultCall = null; return false; } RoslynDebug.Assert(awaiterType is object); if (getAwaiterGetResultCall.Kind != BoundKind.Call) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, node, awaiterType, WellKnownMemberNames.GetResult); getResultMethod = null; getAwaiterGetResultCall = null; return false; } getResultMethod = ((BoundCall)getAwaiterGetResultCall).Method; if (getResultMethod.IsExtensionMethod) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, node, awaiterType, WellKnownMemberNames.GetResult); getResultMethod = null; getAwaiterGetResultCall = null; return false; } if (HasOptionalOrVariableParameters(getResultMethod) || getResultMethod.IsConditional) { Error(diagnostics, ErrorCode.ERR_BadAwaiterPattern, node, awaiterType, awaitedExpressionType); getResultMethod = null; getAwaiterGetResultCall = null; return false; } // The lack of a GetResult method will be reported by ValidateGetResult(). return true; } private static bool HasOptionalOrVariableParameters(MethodSymbol method) { RoslynDebug.Assert(method != null); if (method.ParameterCount != 0) { var parameter = method.Parameters[method.ParameterCount - 1]; return parameter.IsOptional || parameter.IsParams; } return false; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/Core/Portable/RQName/Nodes/RQExplicitInterfaceMemberName.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 Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQExplicitInterfaceMemberName : RQMethodPropertyOrEventName { public readonly RQType InterfaceType; public readonly RQOrdinaryMethodPropertyOrEventName Name; public RQExplicitInterfaceMemberName(RQType interfaceType, RQOrdinaryMethodPropertyOrEventName name) { InterfaceType = interfaceType; Name = name; } public override string OrdinaryNameValue { get { return Name.OrdinaryNameValue; } } public override SimpleGroupNode ToSimpleTree() => new(RQNameStrings.IntfExplName, InterfaceType.ToSimpleTree(), Name.ToSimpleTree()); } }
// 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 Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQExplicitInterfaceMemberName : RQMethodPropertyOrEventName { public readonly RQType InterfaceType; public readonly RQOrdinaryMethodPropertyOrEventName Name; public RQExplicitInterfaceMemberName(RQType interfaceType, RQOrdinaryMethodPropertyOrEventName name) { InterfaceType = interfaceType; Name = name; } public override string OrdinaryNameValue { get { return Name.OrdinaryNameValue; } } public override SimpleGroupNode ToSimpleTree() => new(RQNameStrings.IntfExplName, InterfaceType.ToSimpleTree(), Name.ToSimpleTree()); } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/EditorFeatures/VisualBasic/FindUsages/VisualBasicFindUsagesLSPService.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.Composition Imports Microsoft.CodeAnalysis.Editor.FindUsages Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.FindUsages <ExportLanguageService(GetType(IFindUsagesLSPService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicFindUsagesLSPService Inherits AbstractFindUsagesService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() 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.Composition Imports Microsoft.CodeAnalysis.Editor.FindUsages Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.FindUsages <ExportLanguageService(GetType(IFindUsagesLSPService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicFindUsagesLSPService Inherits AbstractFindUsagesService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/VisualStudio/Xaml/Impl/Features/OrganizeImports/IXamlOrganizeNamespacesService.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; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.CodeAnalysis.Editor.Xaml.Features.OrganizeImports { internal interface IXamlOrganizeNamespacesService { /// <returns>Returns the rewritten document, or the document passed in if no changes were made. If cancellation /// was observed, it returns null.</returns> Task<Document> OrganizeNamespacesAsync(Document document, bool placeSystemNamespaceFirst, 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.CodeAnalysis.Editor.Xaml.Features.OrganizeImports { internal interface IXamlOrganizeNamespacesService { /// <returns>Returns the rewritten document, or the document passed in if no changes were made. If cancellation /// was observed, it returns null.</returns> Task<Document> OrganizeNamespacesAsync(Document document, bool placeSystemNamespaceFirst, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Core/Portable/SpecialTypeExtensions.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal static class SpecialTypeExtensions { /// <summary> /// Checks if a type is considered a "built-in integral" by CLR. /// </summary> public static bool IsClrInteger(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return true; default: return false; } } /// <summary> /// Checks if a type is a primitive of a fixed size. /// </summary> public static bool IsBlittable(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: return true; default: return false; } } public static bool IsValueType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Void: case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: case SpecialType.System_Nullable_T: case SpecialType.System_DateTime: case SpecialType.System_TypedReference: case SpecialType.System_ArgIterator: case SpecialType.System_RuntimeArgumentHandle: case SpecialType.System_RuntimeFieldHandle: case SpecialType.System_RuntimeMethodHandle: case SpecialType.System_RuntimeTypeHandle: return true; default: return false; } } public static int SizeInBytes(this SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return sizeof(sbyte); case SpecialType.System_Byte: return sizeof(byte); case SpecialType.System_Int16: return sizeof(short); case SpecialType.System_UInt16: return sizeof(ushort); case SpecialType.System_Int32: return sizeof(int); case SpecialType.System_UInt32: return sizeof(uint); case SpecialType.System_Int64: return sizeof(long); case SpecialType.System_UInt64: return sizeof(ulong); case SpecialType.System_Char: return sizeof(char); case SpecialType.System_Single: return sizeof(float); case SpecialType.System_Double: return sizeof(double); case SpecialType.System_Boolean: return sizeof(bool); case SpecialType.System_Decimal: //This isn't in the spec, but it is handled by dev10 return sizeof(decimal); default: // invalid return 0; } } /// <summary> /// These special types are structs that contain fields of the same type /// (e.g. System.Int32 contains a field of type System.Int32). /// </summary> public static bool IsPrimitiveRecursiveStruct(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Double: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: case SpecialType.System_SByte: case SpecialType.System_Single: return true; default: return false; } } public static bool IsValidEnumUnderlyingType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; default: return false; } } public static bool IsNumericType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: return true; default: return false; } } /// <summary> /// Checks if a type is considered a "built-in integral" by CLR. /// </summary> public static bool IsIntegralType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; default: return false; } } public static bool IsUnsignedIntegralType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: return true; default: return false; } } public static bool IsSignedIntegralType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: return true; default: return false; } } /// <summary> /// For signed integer types return number of bits for their representation minus 1. /// I.e. 7 for Int8, 31 for Int32, etc. /// Used for checking loop end condition for VB for loop. /// </summary> public static int VBForToShiftBits(this SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return 7; case SpecialType.System_Int16: return 15; case SpecialType.System_Int32: return 31; case SpecialType.System_Int64: return 63; default: throw Roslyn.Utilities.ExceptionUtilities.UnexpectedValue(specialType); } } public static SpecialType FromRuntimeTypeOfLiteralValue(object value) { RoslynDebug.Assert(value != null); // Perf: Note that JIT optimizes each expression val.GetType() == typeof(T) to a single register comparison. // Also the checks are sorted by commonality of the checked types. if (value.GetType() == typeof(int)) { return SpecialType.System_Int32; } if (value.GetType() == typeof(string)) { return SpecialType.System_String; } if (value.GetType() == typeof(bool)) { return SpecialType.System_Boolean; } if (value.GetType() == typeof(char)) { return SpecialType.System_Char; } if (value.GetType() == typeof(long)) { return SpecialType.System_Int64; } if (value.GetType() == typeof(double)) { return SpecialType.System_Double; } if (value.GetType() == typeof(uint)) { return SpecialType.System_UInt32; } if (value.GetType() == typeof(ulong)) { return SpecialType.System_UInt64; } if (value.GetType() == typeof(float)) { return SpecialType.System_Single; } if (value.GetType() == typeof(decimal)) { return SpecialType.System_Decimal; } if (value.GetType() == typeof(short)) { return SpecialType.System_Int16; } if (value.GetType() == typeof(ushort)) { return SpecialType.System_UInt16; } if (value.GetType() == typeof(DateTime)) { return SpecialType.System_DateTime; } if (value.GetType() == typeof(byte)) { return SpecialType.System_Byte; } if (value.GetType() == typeof(sbyte)) { return SpecialType.System_SByte; } return SpecialType.None; } } }
// 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal static class SpecialTypeExtensions { /// <summary> /// Checks if a type is considered a "built-in integral" by CLR. /// </summary> public static bool IsClrInteger(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return true; default: return false; } } /// <summary> /// Checks if a type is a primitive of a fixed size. /// </summary> public static bool IsBlittable(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: return true; default: return false; } } public static bool IsValueType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Void: case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: case SpecialType.System_Nullable_T: case SpecialType.System_DateTime: case SpecialType.System_TypedReference: case SpecialType.System_ArgIterator: case SpecialType.System_RuntimeArgumentHandle: case SpecialType.System_RuntimeFieldHandle: case SpecialType.System_RuntimeMethodHandle: case SpecialType.System_RuntimeTypeHandle: return true; default: return false; } } public static int SizeInBytes(this SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return sizeof(sbyte); case SpecialType.System_Byte: return sizeof(byte); case SpecialType.System_Int16: return sizeof(short); case SpecialType.System_UInt16: return sizeof(ushort); case SpecialType.System_Int32: return sizeof(int); case SpecialType.System_UInt32: return sizeof(uint); case SpecialType.System_Int64: return sizeof(long); case SpecialType.System_UInt64: return sizeof(ulong); case SpecialType.System_Char: return sizeof(char); case SpecialType.System_Single: return sizeof(float); case SpecialType.System_Double: return sizeof(double); case SpecialType.System_Boolean: return sizeof(bool); case SpecialType.System_Decimal: //This isn't in the spec, but it is handled by dev10 return sizeof(decimal); default: // invalid return 0; } } /// <summary> /// These special types are structs that contain fields of the same type /// (e.g. System.Int32 contains a field of type System.Int32). /// </summary> public static bool IsPrimitiveRecursiveStruct(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Double: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: case SpecialType.System_SByte: case SpecialType.System_Single: return true; default: return false; } } public static bool IsValidEnumUnderlyingType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; default: return false; } } public static bool IsNumericType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: return true; default: return false; } } /// <summary> /// Checks if a type is considered a "built-in integral" by CLR. /// </summary> public static bool IsIntegralType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; default: return false; } } public static bool IsUnsignedIntegralType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: return true; default: return false; } } public static bool IsSignedIntegralType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: return true; default: return false; } } /// <summary> /// For signed integer types return number of bits for their representation minus 1. /// I.e. 7 for Int8, 31 for Int32, etc. /// Used for checking loop end condition for VB for loop. /// </summary> public static int VBForToShiftBits(this SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return 7; case SpecialType.System_Int16: return 15; case SpecialType.System_Int32: return 31; case SpecialType.System_Int64: return 63; default: throw Roslyn.Utilities.ExceptionUtilities.UnexpectedValue(specialType); } } public static SpecialType FromRuntimeTypeOfLiteralValue(object value) { RoslynDebug.Assert(value != null); // Perf: Note that JIT optimizes each expression val.GetType() == typeof(T) to a single register comparison. // Also the checks are sorted by commonality of the checked types. if (value.GetType() == typeof(int)) { return SpecialType.System_Int32; } if (value.GetType() == typeof(string)) { return SpecialType.System_String; } if (value.GetType() == typeof(bool)) { return SpecialType.System_Boolean; } if (value.GetType() == typeof(char)) { return SpecialType.System_Char; } if (value.GetType() == typeof(long)) { return SpecialType.System_Int64; } if (value.GetType() == typeof(double)) { return SpecialType.System_Double; } if (value.GetType() == typeof(uint)) { return SpecialType.System_UInt32; } if (value.GetType() == typeof(ulong)) { return SpecialType.System_UInt64; } if (value.GetType() == typeof(float)) { return SpecialType.System_Single; } if (value.GetType() == typeof(decimal)) { return SpecialType.System_Decimal; } if (value.GetType() == typeof(short)) { return SpecialType.System_Int16; } if (value.GetType() == typeof(ushort)) { return SpecialType.System_UInt16; } if (value.GetType() == typeof(DateTime)) { return SpecialType.System_DateTime; } if (value.GetType() == typeof(byte)) { return SpecialType.System_Byte; } if (value.GetType() == typeof(sbyte)) { return SpecialType.System_SByte; } return SpecialType.None; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/Core/Portable/Common/GlyphExtensions.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.Immutable; using Microsoft.CodeAnalysis.Tags; namespace Microsoft.CodeAnalysis { internal static class GlyphExtensions { public static ImmutableArray<Glyph> GetGlyphs(this ImmutableArray<string> tags) { var builder = ImmutableArray.CreateBuilder<Glyph>(initialCapacity: tags.Length); foreach (var tag in tags) { var glyph = GetGlyph(tag, tags); if (glyph != Glyph.None) { builder.Add(glyph); } } return builder.ToImmutable(); } public static Glyph GetFirstGlyph(this ImmutableArray<string> tags) { var glyphs = GetGlyphs(tags); return !glyphs.IsEmpty ? glyphs[0] : Glyph.None; } private static Glyph GetGlyph(string tag, ImmutableArray<string> allTags) { switch (tag) { case WellKnownTags.Assembly: return Glyph.Assembly; case WellKnownTags.File: return allTags.Contains(LanguageNames.VisualBasic) ? Glyph.BasicFile : Glyph.CSharpFile; case WellKnownTags.Project: return allTags.Contains(LanguageNames.VisualBasic) ? Glyph.BasicProject : Glyph.CSharpProject; case WellKnownTags.Class: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.ClassProtected, Accessibility.Private => Glyph.ClassPrivate, Accessibility.Internal => Glyph.ClassInternal, _ => Glyph.ClassPublic, }; case WellKnownTags.Constant: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.ConstantProtected, Accessibility.Private => Glyph.ConstantPrivate, Accessibility.Internal => Glyph.ConstantInternal, _ => Glyph.ConstantPublic, }; case WellKnownTags.Delegate: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.DelegateProtected, Accessibility.Private => Glyph.DelegatePrivate, Accessibility.Internal => Glyph.DelegateInternal, _ => Glyph.DelegatePublic, }; case WellKnownTags.Enum: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.EnumProtected, Accessibility.Private => Glyph.EnumPrivate, Accessibility.Internal => Glyph.EnumInternal, _ => Glyph.EnumPublic, }; case WellKnownTags.EnumMember: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.EnumMemberProtected, Accessibility.Private => Glyph.EnumMemberPrivate, Accessibility.Internal => Glyph.EnumMemberInternal, _ => Glyph.EnumMemberPublic, }; case WellKnownTags.Error: return Glyph.Error; case WellKnownTags.Event: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.EventProtected, Accessibility.Private => Glyph.EventPrivate, Accessibility.Internal => Glyph.EventInternal, _ => Glyph.EventPublic, }; case WellKnownTags.ExtensionMethod: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.ExtensionMethodProtected, Accessibility.Private => Glyph.ExtensionMethodPrivate, Accessibility.Internal => Glyph.ExtensionMethodInternal, _ => Glyph.ExtensionMethodPublic, }; case WellKnownTags.Field: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.FieldProtected, Accessibility.Private => Glyph.FieldPrivate, Accessibility.Internal => Glyph.FieldInternal, _ => Glyph.FieldPublic, }; case WellKnownTags.Interface: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.InterfaceProtected, Accessibility.Private => Glyph.InterfacePrivate, Accessibility.Internal => Glyph.InterfaceInternal, _ => Glyph.InterfacePublic, }; case WellKnownTags.TargetTypeMatch: return Glyph.TargetTypeMatch; case WellKnownTags.Intrinsic: return Glyph.Intrinsic; case WellKnownTags.Keyword: return Glyph.Keyword; case WellKnownTags.Label: return Glyph.Label; case WellKnownTags.Local: return Glyph.Local; case WellKnownTags.Namespace: return Glyph.Namespace; case WellKnownTags.Method: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.MethodProtected, Accessibility.Private => Glyph.MethodPrivate, Accessibility.Internal => Glyph.MethodInternal, _ => Glyph.MethodPublic, }; case WellKnownTags.Module: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.ModulePublic, Accessibility.Private => Glyph.ModulePrivate, Accessibility.Internal => Glyph.ModuleInternal, _ => Glyph.ModulePublic, }; case WellKnownTags.Folder: return Glyph.OpenFolder; case WellKnownTags.Operator: return Glyph.Operator; case WellKnownTags.Parameter: return Glyph.Parameter; case WellKnownTags.Property: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.PropertyProtected, Accessibility.Private => Glyph.PropertyPrivate, Accessibility.Internal => Glyph.PropertyInternal, _ => Glyph.PropertyPublic, }; case WellKnownTags.RangeVariable: return Glyph.RangeVariable; case WellKnownTags.Reference: return Glyph.Reference; case WellKnownTags.NuGet: return Glyph.NuGet; case WellKnownTags.Structure: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.StructureProtected, Accessibility.Private => Glyph.StructurePrivate, Accessibility.Internal => Glyph.StructureInternal, _ => Glyph.StructurePublic, }; case WellKnownTags.TypeParameter: return Glyph.TypeParameter; case WellKnownTags.Snippet: return Glyph.Snippet; case WellKnownTags.Warning: return Glyph.CompletionWarning; case WellKnownTags.StatusInformation: return Glyph.StatusInformation; } return Glyph.None; } public static Accessibility GetAccessibility(ImmutableArray<string> tags) { foreach (var tag in tags) { switch (tag) { case WellKnownTags.Public: return Accessibility.Public; case WellKnownTags.Protected: return Accessibility.Protected; case WellKnownTags.Internal: return Accessibility.Internal; case WellKnownTags.Private: return Accessibility.Private; } } return Accessibility.NotApplicable; } } }
// 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.Immutable; using Microsoft.CodeAnalysis.Tags; namespace Microsoft.CodeAnalysis { internal static class GlyphExtensions { public static ImmutableArray<Glyph> GetGlyphs(this ImmutableArray<string> tags) { var builder = ImmutableArray.CreateBuilder<Glyph>(initialCapacity: tags.Length); foreach (var tag in tags) { var glyph = GetGlyph(tag, tags); if (glyph != Glyph.None) { builder.Add(glyph); } } return builder.ToImmutable(); } public static Glyph GetFirstGlyph(this ImmutableArray<string> tags) { var glyphs = GetGlyphs(tags); return !glyphs.IsEmpty ? glyphs[0] : Glyph.None; } private static Glyph GetGlyph(string tag, ImmutableArray<string> allTags) { switch (tag) { case WellKnownTags.Assembly: return Glyph.Assembly; case WellKnownTags.File: return allTags.Contains(LanguageNames.VisualBasic) ? Glyph.BasicFile : Glyph.CSharpFile; case WellKnownTags.Project: return allTags.Contains(LanguageNames.VisualBasic) ? Glyph.BasicProject : Glyph.CSharpProject; case WellKnownTags.Class: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.ClassProtected, Accessibility.Private => Glyph.ClassPrivate, Accessibility.Internal => Glyph.ClassInternal, _ => Glyph.ClassPublic, }; case WellKnownTags.Constant: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.ConstantProtected, Accessibility.Private => Glyph.ConstantPrivate, Accessibility.Internal => Glyph.ConstantInternal, _ => Glyph.ConstantPublic, }; case WellKnownTags.Delegate: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.DelegateProtected, Accessibility.Private => Glyph.DelegatePrivate, Accessibility.Internal => Glyph.DelegateInternal, _ => Glyph.DelegatePublic, }; case WellKnownTags.Enum: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.EnumProtected, Accessibility.Private => Glyph.EnumPrivate, Accessibility.Internal => Glyph.EnumInternal, _ => Glyph.EnumPublic, }; case WellKnownTags.EnumMember: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.EnumMemberProtected, Accessibility.Private => Glyph.EnumMemberPrivate, Accessibility.Internal => Glyph.EnumMemberInternal, _ => Glyph.EnumMemberPublic, }; case WellKnownTags.Error: return Glyph.Error; case WellKnownTags.Event: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.EventProtected, Accessibility.Private => Glyph.EventPrivate, Accessibility.Internal => Glyph.EventInternal, _ => Glyph.EventPublic, }; case WellKnownTags.ExtensionMethod: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.ExtensionMethodProtected, Accessibility.Private => Glyph.ExtensionMethodPrivate, Accessibility.Internal => Glyph.ExtensionMethodInternal, _ => Glyph.ExtensionMethodPublic, }; case WellKnownTags.Field: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.FieldProtected, Accessibility.Private => Glyph.FieldPrivate, Accessibility.Internal => Glyph.FieldInternal, _ => Glyph.FieldPublic, }; case WellKnownTags.Interface: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.InterfaceProtected, Accessibility.Private => Glyph.InterfacePrivate, Accessibility.Internal => Glyph.InterfaceInternal, _ => Glyph.InterfacePublic, }; case WellKnownTags.TargetTypeMatch: return Glyph.TargetTypeMatch; case WellKnownTags.Intrinsic: return Glyph.Intrinsic; case WellKnownTags.Keyword: return Glyph.Keyword; case WellKnownTags.Label: return Glyph.Label; case WellKnownTags.Local: return Glyph.Local; case WellKnownTags.Namespace: return Glyph.Namespace; case WellKnownTags.Method: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.MethodProtected, Accessibility.Private => Glyph.MethodPrivate, Accessibility.Internal => Glyph.MethodInternal, _ => Glyph.MethodPublic, }; case WellKnownTags.Module: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.ModulePublic, Accessibility.Private => Glyph.ModulePrivate, Accessibility.Internal => Glyph.ModuleInternal, _ => Glyph.ModulePublic, }; case WellKnownTags.Folder: return Glyph.OpenFolder; case WellKnownTags.Operator: return Glyph.Operator; case WellKnownTags.Parameter: return Glyph.Parameter; case WellKnownTags.Property: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.PropertyProtected, Accessibility.Private => Glyph.PropertyPrivate, Accessibility.Internal => Glyph.PropertyInternal, _ => Glyph.PropertyPublic, }; case WellKnownTags.RangeVariable: return Glyph.RangeVariable; case WellKnownTags.Reference: return Glyph.Reference; case WellKnownTags.NuGet: return Glyph.NuGet; case WellKnownTags.Structure: return (GetAccessibility(allTags)) switch { Accessibility.Protected => Glyph.StructureProtected, Accessibility.Private => Glyph.StructurePrivate, Accessibility.Internal => Glyph.StructureInternal, _ => Glyph.StructurePublic, }; case WellKnownTags.TypeParameter: return Glyph.TypeParameter; case WellKnownTags.Snippet: return Glyph.Snippet; case WellKnownTags.Warning: return Glyph.CompletionWarning; case WellKnownTags.StatusInformation: return Glyph.StatusInformation; } return Glyph.None; } public static Accessibility GetAccessibility(ImmutableArray<string> tags) { foreach (var tag in tags) { switch (tag) { case WellKnownTags.Public: return Accessibility.Public; case WellKnownTags.Protected: return Accessibility.Protected; case WellKnownTags.Internal: return Accessibility.Internal; case WellKnownTags.Private: return Accessibility.Private; } } return Accessibility.NotApplicable; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/EditorFeatures/CSharpTest2/Recommendations/InitKeywordRecommenderTests.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.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public class InitKeywordRecommenderTests : KeywordRecommenderTests { [Fact] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact] 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] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int Goo { $$"); } [Fact] public async Task TestAfterPropertyPrivate() { await VerifyKeywordAsync( @"class C { int Goo { private $$"); } [Fact] public async Task TestAfterPropertyAttribute() { await VerifyKeywordAsync( @"class C { int Goo { [Bar] $$"); } [Fact] public async Task TestAfterPropertyAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { [Bar] private $$"); } [Fact] public async Task TestAfterPropertyGet() { await VerifyKeywordAsync( @"class C { int Goo { get; $$"); } [Fact] public async Task TestAfterPropertyGetAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get; private $$"); } [Fact] public async Task TestAfterPropertyGetAndAttribute() { await VerifyKeywordAsync( @"class C { int Goo { get; [Bar] $$"); } [Fact] public async Task TestAfterPropertyGetAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get; [Bar] private $$"); } [Fact] public async Task TestAfterGetAccessorBlock() { await VerifyKeywordAsync( @"class C { int Goo { get { } $$"); } [Fact] public async Task TestAfterSetAccessorBlock() { await VerifyKeywordAsync( @"class C { int Goo { set { } $$"); } [Fact] public async Task TestAfterGetAccessorBlockAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get { } private $$"); } [Fact] public async Task TestAfterGetAccessorBlockAndAttribute() { await VerifyKeywordAsync( @"class C { int Goo { get { } [Bar] $$"); } [Fact] public async Task TestAfterGetAccessorBlockAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get { } [Bar] private $$"); } [Fact] public async Task TestNotAfterPropertySetKeyword() { await VerifyAbsenceAsync( @"class C { int Goo { set $$"); } [Fact] public async Task TestAfterPropertySetAccessor() { await VerifyKeywordAsync( @"class C { int Goo { set; $$"); } [Fact] public async Task TestNotInEvent() { await VerifyAbsenceAsync( @"class C { event Goo E { $$"); } [Fact] public async Task TestAfterIndexer() { await VerifyKeywordAsync( @"class C { int this[int i] { $$"); } [Fact] public async Task TestAfterIndexerPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { private $$"); } [Fact] public async Task TestAfterIndexerAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { [Bar] $$"); } [Fact] public async Task TestAfterIndexerAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { [Bar] private $$"); } [Fact] public async Task TestAfterIndexerGet() { await VerifyKeywordAsync( @"class C { int this[int i] { get; $$"); } [Fact] public async Task TestAfterIndexerGetAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get; private $$"); } [Fact] public async Task TestAfterIndexerGetAndAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { get; [Bar] $$"); } [Fact] public async Task TestAfterIndexerGetAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get; [Bar] private $$"); } [Fact] public async Task TestAfterIndexerGetBlock() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } $$"); } [Fact] public async Task TestAfterIndexerGetBlockAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } private $$"); } [Fact] public async Task TestAfterIndexerGetBlockAndAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } [Bar] $$"); } [Fact] public async Task TestAfterIndexerGetBlockAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } [Bar] private $$"); } [Fact] public async Task TestNotAfterIndexerSetKeyword() { await VerifyAbsenceAsync( @"class C { int this[int i] { set $$"); } [Fact] public async Task TestAfterIndexerSetAccessor() { await VerifyKeywordAsync( @"class C { int this[int i] { set; $$"); } } }
// 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.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public class InitKeywordRecommenderTests : KeywordRecommenderTests { [Fact] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact] 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] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int Goo { $$"); } [Fact] public async Task TestAfterPropertyPrivate() { await VerifyKeywordAsync( @"class C { int Goo { private $$"); } [Fact] public async Task TestAfterPropertyAttribute() { await VerifyKeywordAsync( @"class C { int Goo { [Bar] $$"); } [Fact] public async Task TestAfterPropertyAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { [Bar] private $$"); } [Fact] public async Task TestAfterPropertyGet() { await VerifyKeywordAsync( @"class C { int Goo { get; $$"); } [Fact] public async Task TestAfterPropertyGetAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get; private $$"); } [Fact] public async Task TestAfterPropertyGetAndAttribute() { await VerifyKeywordAsync( @"class C { int Goo { get; [Bar] $$"); } [Fact] public async Task TestAfterPropertyGetAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get; [Bar] private $$"); } [Fact] public async Task TestAfterGetAccessorBlock() { await VerifyKeywordAsync( @"class C { int Goo { get { } $$"); } [Fact] public async Task TestAfterSetAccessorBlock() { await VerifyKeywordAsync( @"class C { int Goo { set { } $$"); } [Fact] public async Task TestAfterGetAccessorBlockAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get { } private $$"); } [Fact] public async Task TestAfterGetAccessorBlockAndAttribute() { await VerifyKeywordAsync( @"class C { int Goo { get { } [Bar] $$"); } [Fact] public async Task TestAfterGetAccessorBlockAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get { } [Bar] private $$"); } [Fact] public async Task TestNotAfterPropertySetKeyword() { await VerifyAbsenceAsync( @"class C { int Goo { set $$"); } [Fact] public async Task TestAfterPropertySetAccessor() { await VerifyKeywordAsync( @"class C { int Goo { set; $$"); } [Fact] public async Task TestNotInEvent() { await VerifyAbsenceAsync( @"class C { event Goo E { $$"); } [Fact] public async Task TestAfterIndexer() { await VerifyKeywordAsync( @"class C { int this[int i] { $$"); } [Fact] public async Task TestAfterIndexerPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { private $$"); } [Fact] public async Task TestAfterIndexerAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { [Bar] $$"); } [Fact] public async Task TestAfterIndexerAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { [Bar] private $$"); } [Fact] public async Task TestAfterIndexerGet() { await VerifyKeywordAsync( @"class C { int this[int i] { get; $$"); } [Fact] public async Task TestAfterIndexerGetAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get; private $$"); } [Fact] public async Task TestAfterIndexerGetAndAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { get; [Bar] $$"); } [Fact] public async Task TestAfterIndexerGetAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get; [Bar] private $$"); } [Fact] public async Task TestAfterIndexerGetBlock() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } $$"); } [Fact] public async Task TestAfterIndexerGetBlockAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } private $$"); } [Fact] public async Task TestAfterIndexerGetBlockAndAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } [Bar] $$"); } [Fact] public async Task TestAfterIndexerGetBlockAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } [Bar] private $$"); } [Fact] public async Task TestNotAfterIndexerSetKeyword() { await VerifyAbsenceAsync( @"class C { int this[int i] { set $$"); } [Fact] public async Task TestAfterIndexerSetAccessor() { await VerifyKeywordAsync( @"class C { int this[int i] { set; $$"); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/UShortKeywordRecommender.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.Threading; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class UShortKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public UShortKeywordRecommender() : base(SyntaxKind.UShortKeyword) { } /// <summary> /// We set the <see cref="MatchPriority"/> of this item less than the default value so that /// completion selects the <see langword="using"/> keyword over it as the user starts typing. /// </summary> protected override int DefaultMatchPriority => MatchPriority.Default - 1; protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.GetRequiredParent().HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsEnumBaseListContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_UInt16; } }
// 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.Threading; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class UShortKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public UShortKeywordRecommender() : base(SyntaxKind.UShortKeyword) { } /// <summary> /// We set the <see cref="MatchPriority"/> of this item less than the default value so that /// completion selects the <see langword="using"/> keyword over it as the user starts typing. /// </summary> protected override int DefaultMatchPriority => MatchPriority.Default - 1; protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.GetRequiredParent().HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsEnumBaseListContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_UInt16; } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/CSharp/Portable/Wrapping/SeparatedSyntaxList/AbstractCSharpSeparatedSyntaxListWrapper.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.Indentation; using Microsoft.CodeAnalysis.Wrapping.SeparatedSyntaxList; namespace Microsoft.CodeAnalysis.CSharp.Wrapping.SeparatedSyntaxList { internal abstract class AbstractCSharpSeparatedSyntaxListWrapper<TListSyntax, TListItemSyntax> : AbstractSeparatedSyntaxListWrapper<TListSyntax, TListItemSyntax> where TListSyntax : SyntaxNode where TListItemSyntax : SyntaxNode { protected AbstractCSharpSeparatedSyntaxListWrapper() : base(CSharpIndentationService.Instance) { } } }
// 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.Indentation; using Microsoft.CodeAnalysis.Wrapping.SeparatedSyntaxList; namespace Microsoft.CodeAnalysis.CSharp.Wrapping.SeparatedSyntaxList { internal abstract class AbstractCSharpSeparatedSyntaxListWrapper<TListSyntax, TListItemSyntax> : AbstractSeparatedSyntaxListWrapper<TListSyntax, TListItemSyntax> where TListSyntax : SyntaxNode where TListItemSyntax : SyntaxNode { protected AbstractCSharpSeparatedSyntaxListWrapper() : base(CSharpIndentationService.Instance) { } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/VisualStudio/CSharp/Test/CallHierarchy/CSharpCallHierarchyTests.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.Editor.UnitTests.CallHierarchy; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CallHierarchy { [UseExportProvider] public class CSharpCallHierarchyTests { [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InvokeOnMethod() { var text = @" namespace N { class C { void G$$oo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InvokeOnProperty() { var text = @" namespace N { class C { public int G$$oo { get; set;} } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InvokeOnEvent() { var text = @" using System; namespace N { class C { public event EventHandler Go$$o; } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_FindCalls() { var text = @" namespace N { class C { void G$$oo() { } } class G { void Main() { var c = new C(); c.Goo(); } void Main2() { var c = new C(); c.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main()", "N.G.Main2()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_InterfaceImplementation() { var text = @" namespace N { interface I { void Goo(); } class C : I { public void G$$oo() { } } class G { void Main() { I c = new C(); c.Goo(); } void Main2() { var c = new C(); c.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Goo()") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main2()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Goo()"), new[] { "N.G.Main()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_CallToOverride() { var text = @" namespace N { class C { protected virtual void G$$oo() { } } class D : C { protected override void Goo() { } void Bar() { C c; c.Goo() } void Baz() { D d; d.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), EditorFeaturesResources.Calls_To_Overrides }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.D.Bar()" }); testState.VerifyResult(root, EditorFeaturesResources.Calls_To_Overrides, new[] { "N.D.Baz()" }); } [WpfFact, WorkItem(829705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829705"), Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_CallToBase() { var text = @" namespace N { class C { protected virtual void Goo() { } } class D : C { protected override void Goo() { } void Bar() { C c; c.Goo() } void Baz() { D d; d.Go$$o(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.D.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Goo()") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.D.Baz()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Goo()"), new[] { "N.D.Bar()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void FieldInitializers() { var text = @" namespace N { class C { public int goo = Goo(); protected int Goo$$() { return 0; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo") }); testState.VerifyResultName(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { EditorFeaturesResources.Initializers }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void FieldReferences() { var text = @" namespace N { class C { public int g$$oo = Goo(); protected int Goo() { goo = 3; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.goo", new[] { string.Format(EditorFeaturesResources.References_To_Field_0, "goo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.References_To_Field_0, "goo"), new[] { "N.C.Goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void PropertyGet() { var text = @" namespace N { class C { public int val { g$$et { return 0; } } public int goo() { var x = this.val; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.val.get", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "get_val") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "get_val"), new[] { "N.C.goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Generic() { var text = @" namespace N { class C { public int gen$$eric<T>(this string generic, ref T stuff) { return 0; } public int goo() { int i; generic("", ref i); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.generic<T>(this string, ref T)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "generic") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "generic"), new[] { "N.C.goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void ExtensionMethods() { var text = @" namespace ConsoleApplication10 { class Program { static void Main(string[] args) { var x = ""string""; x.BarStr$$ing(); } } public static class Extensions { public static string BarString(this string s) { return s; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "ConsoleApplication10.Extensions.BarString(this string)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "BarString") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "BarString"), new[] { "ConsoleApplication10.Program.Main(string[])" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void GenericExtensionMethods() { var text = @" using System.Collections.Generic; using System.Linq; namespace N { class Program { static void Main(string[] args) { List<int> x = new List<int>(); var z = x.Si$$ngle(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "System.Linq.Enumerable.Single<TSource>(this System.Collections.Generic.IEnumerable<TSource>)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Single") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Single"), new[] { "N.Program.Main(string[])" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InterfaceImplementors() { var text = @" namespace N { interface I { void Go$$o(); } class C : I { public async Task Goo() { } } class G { void Main() { I c = new C(); c.Goo(); } void Main2() { var c = new C(); c.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.I.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Implements_0, "Goo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Implements_0, "Goo"), new[] { "N.C.Goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void NoFindOverridesOnSealedMethod() { var text = @" namespace N { class C { void G$$oo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); Assert.DoesNotContain("Overrides", root.SupportedSearchCategories.Select(s => s.DisplayName)); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void FindOverrides() { var text = @" namespace N { class C { public virtual void G$$oo() { } } class G : C { public override void Goo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), EditorFeaturesResources.Overrides_ }); testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "N.G.Goo()" }); } [WorkItem(844613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844613")] [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void AbstractMethodInclusionToOverrides() { var text = @" using System; abstract class Base { public abstract void $$M(); } class Derived : Base { public override void M() { throw new NotImplementedException(); } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "Base.M()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "M"), EditorFeaturesResources.Overrides_, EditorFeaturesResources.Calls_To_Overrides }); testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "Derived.M()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void SearchAfterEditWorks() { var text = @" namespace N { class C { void G$$oo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.Workspace.Documents.Single().GetTextBuffer().Insert(0, "/* hello */"); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), expectedCallers: new[] { "N.C.Goo()" }); } } }
// 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.Editor.UnitTests.CallHierarchy; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CallHierarchy { [UseExportProvider] public class CSharpCallHierarchyTests { [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InvokeOnMethod() { var text = @" namespace N { class C { void G$$oo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InvokeOnProperty() { var text = @" namespace N { class C { public int G$$oo { get; set;} } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InvokeOnEvent() { var text = @" using System; namespace N { class C { public event EventHandler Go$$o; } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_FindCalls() { var text = @" namespace N { class C { void G$$oo() { } } class G { void Main() { var c = new C(); c.Goo(); } void Main2() { var c = new C(); c.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main()", "N.G.Main2()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_InterfaceImplementation() { var text = @" namespace N { interface I { void Goo(); } class C : I { public void G$$oo() { } } class G { void Main() { I c = new C(); c.Goo(); } void Main2() { var c = new C(); c.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Goo()") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main2()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Goo()"), new[] { "N.G.Main()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_CallToOverride() { var text = @" namespace N { class C { protected virtual void G$$oo() { } } class D : C { protected override void Goo() { } void Bar() { C c; c.Goo() } void Baz() { D d; d.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), EditorFeaturesResources.Calls_To_Overrides }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.D.Bar()" }); testState.VerifyResult(root, EditorFeaturesResources.Calls_To_Overrides, new[] { "N.D.Baz()" }); } [WpfFact, WorkItem(829705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829705"), Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_CallToBase() { var text = @" namespace N { class C { protected virtual void Goo() { } } class D : C { protected override void Goo() { } void Bar() { C c; c.Goo() } void Baz() { D d; d.Go$$o(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.D.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Goo()") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.D.Baz()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Goo()"), new[] { "N.D.Bar()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void FieldInitializers() { var text = @" namespace N { class C { public int goo = Goo(); protected int Goo$$() { return 0; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo") }); testState.VerifyResultName(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { EditorFeaturesResources.Initializers }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void FieldReferences() { var text = @" namespace N { class C { public int g$$oo = Goo(); protected int Goo() { goo = 3; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.goo", new[] { string.Format(EditorFeaturesResources.References_To_Field_0, "goo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.References_To_Field_0, "goo"), new[] { "N.C.Goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void PropertyGet() { var text = @" namespace N { class C { public int val { g$$et { return 0; } } public int goo() { var x = this.val; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.val.get", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "get_val") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "get_val"), new[] { "N.C.goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Generic() { var text = @" namespace N { class C { public int gen$$eric<T>(this string generic, ref T stuff) { return 0; } public int goo() { int i; generic("", ref i); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.generic<T>(this string, ref T)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "generic") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "generic"), new[] { "N.C.goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void ExtensionMethods() { var text = @" namespace ConsoleApplication10 { class Program { static void Main(string[] args) { var x = ""string""; x.BarStr$$ing(); } } public static class Extensions { public static string BarString(this string s) { return s; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "ConsoleApplication10.Extensions.BarString(this string)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "BarString") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "BarString"), new[] { "ConsoleApplication10.Program.Main(string[])" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void GenericExtensionMethods() { var text = @" using System.Collections.Generic; using System.Linq; namespace N { class Program { static void Main(string[] args) { List<int> x = new List<int>(); var z = x.Si$$ngle(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "System.Linq.Enumerable.Single<TSource>(this System.Collections.Generic.IEnumerable<TSource>)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Single") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Single"), new[] { "N.Program.Main(string[])" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InterfaceImplementors() { var text = @" namespace N { interface I { void Go$$o(); } class C : I { public async Task Goo() { } } class G { void Main() { I c = new C(); c.Goo(); } void Main2() { var c = new C(); c.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.I.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Implements_0, "Goo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Implements_0, "Goo"), new[] { "N.C.Goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void NoFindOverridesOnSealedMethod() { var text = @" namespace N { class C { void G$$oo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); Assert.DoesNotContain("Overrides", root.SupportedSearchCategories.Select(s => s.DisplayName)); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void FindOverrides() { var text = @" namespace N { class C { public virtual void G$$oo() { } } class G : C { public override void Goo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), EditorFeaturesResources.Overrides_ }); testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "N.G.Goo()" }); } [WorkItem(844613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844613")] [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void AbstractMethodInclusionToOverrides() { var text = @" using System; abstract class Base { public abstract void $$M(); } class Derived : Base { public override void M() { throw new NotImplementedException(); } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "Base.M()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "M"), EditorFeaturesResources.Overrides_, EditorFeaturesResources.Calls_To_Overrides }); testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "Derived.M()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void SearchAfterEditWorks() { var text = @" namespace N { class C { void G$$oo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.Workspace.Documents.Single().GetTextBuffer().Insert(0, "/* hello */"); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), expectedCallers: new[] { "N.C.Goo()" }); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/ReduceTokensCodeCleanupProvider.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.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers <ExportCodeCleanupProvider(PredefinedCodeCleanupProviderNames.ReduceTokens, LanguageNames.VisualBasic), [Shared]> <ExtensionOrder(After:=PredefinedCodeCleanupProviderNames.AddMissingTokens, Before:=PredefinedCodeCleanupProviderNames.Format)> Friend Class ReduceTokensCodeCleanupProvider Inherits AbstractTokensCodeCleanupProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="https://github.com/dotnet/roslyn/issues/42820")> Public Sub New() End Sub Public Overrides ReadOnly Property Name As String Get Return PredefinedCodeCleanupProviderNames.ReduceTokens End Get End Property Protected Overrides Function GetRewriterAsync(document As Document, root As SyntaxNode, spans As ImmutableArray(Of TextSpan), workspace As Workspace, cancellationToken As CancellationToken) As Task(Of Rewriter) Return Task.FromResult(Of Rewriter)(New ReduceTokensRewriter(spans, cancellationToken)) End Function Private Class ReduceTokensRewriter Inherits AbstractTokensCodeCleanupProvider.Rewriter Public Sub New(spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken) MyBase.New(spans, cancellationToken) End Sub Public Overrides Function VisitLiteralExpression(node As LiteralExpressionSyntax) As SyntaxNode Dim newNode = DirectCast(MyBase.VisitLiteralExpression(node), LiteralExpressionSyntax) Dim literal As SyntaxToken = newNode.Token Const digitSeparator = "_"c ' Pretty list floating and decimal literals. Select Case literal.Kind Case SyntaxKind.FloatingLiteralToken ' Get the literal identifier text which needs to be pretty listed. Dim idText = literal.GetIdentifierText() ' Compiler has parsed the literal text as single/double value, fetch the string representation of this value. Dim value As Double = 0 Dim valueText As String = GetFloatLiteralValueString(literal, value) + GetTypeCharString(literal.GetTypeCharacter()) If value = 0 OrElse idText.Contains(digitSeparator) Then ' Overflow/underflow case or zero literal, skip pretty listing. Return newNode End If ' If the string representation of the value differs from the identifier text, create a new literal token with same value but pretty listed "valueText". If Not CaseInsensitiveComparison.Equals(valueText, idText) Then Return newNode.ReplaceToken(literal, CreateLiteralToken(literal, valueText, value)) End If Case SyntaxKind.DecimalLiteralToken ' Get the literal identifier text which needs to be pretty listed. Dim idText = literal.GetIdentifierText() Dim value = DirectCast(literal.Value, Decimal) If value = 0 OrElse idText.Contains(digitSeparator) Then ' Overflow/underflow case or zero literal, skip pretty listing. Return newNode End If ' Compiler has parsed the literal text as a decimal value, fetch the string representation of this value. Dim valueText As String = GetDecimalLiteralValueString(value) + GetTypeCharString(literal.GetTypeCharacter()) If Not CaseInsensitiveComparison.Equals(valueText, idText) Then Return newNode.ReplaceToken(literal, CreateLiteralToken(literal, valueText, value)) End If Case SyntaxKind.IntegerLiteralToken ' Get the literal identifier text which needs to be pretty listed. Dim idText = literal.GetIdentifierText() 'The value will only ever be negative when we have a hex or oct value 'it's safe to cast to ULong as we check for negative values later Dim value As ULong = CType(literal.Value, ULong) If value = 0 AndAlso HasOverflow(literal.GetDiagnostics()) Then 'Overflow/underflow, skip pretty listing. Return newNode End If Dim base = literal.GetBase() If Not base.HasValue OrElse idText.Contains(digitSeparator) Then Return newNode End If 'fetch the string representation of this value in the correct base. Dim valueText As String = GetIntegerLiteralValueString(literal.Value, base.Value) + GetTypeCharString(literal.GetTypeCharacter()) If Not CaseInsensitiveComparison.Equals(valueText, idText) Then Return newNode.ReplaceToken(literal, CreateLiteralToken(literal, valueText, value)) End If End Select Return newNode End Function Private Shared Function GetTypeCharString(typeChar As TypeCharacter) As String Select Case typeChar Case TypeCharacter.Single Return "!" Case TypeCharacter.SingleLiteral Return "F" Case TypeCharacter.Double Return "#" Case TypeCharacter.DoubleLiteral Return "R" Case TypeCharacter.Decimal Return "@" Case TypeCharacter.DecimalLiteral Return "D" Case TypeCharacter.Integer Return "%" Case TypeCharacter.IntegerLiteral Return "I" Case TypeCharacter.ShortLiteral Return "S" Case TypeCharacter.Long Return "&" Case TypeCharacter.LongLiteral Return "L" Case TypeCharacter.UIntegerLiteral Return "UI" Case TypeCharacter.UShortLiteral Return "US" Case TypeCharacter.ULongLiteral Return "UL" Case Else Return "" End Select End Function Private Shared Function GetFloatLiteralValueString(literal As SyntaxToken, <Out> ByRef value As Double) As String Dim isSingle As Boolean = literal.GetTypeCharacter() = TypeCharacter.Single OrElse literal.GetTypeCharacter() = TypeCharacter.SingleLiteral ' Get the string representation of the value using The Round-trip ("R") Format Specifier. ' MSDN comments about "R" format specifier: ' The round-trip ("R") format specifier guarantees that a numeric value that is converted to a string will be parsed back into the same numeric value. ' This format is supported only for the Single, Double, and BigInteger types. ' When a Single or Double value is formatted using this specifier, it is first tested using the general format, with 15 digits of precision for a Double and ' 7 digits of precision for a Single. If the value is successfully parsed back to the same numeric value, it is formatted using the general format specifier. ' If the value is not successfully parsed back to the same numeric value, it is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single. ' Hence the possible actual precision values are: ' (a) Single: 7 or 9 and ' (b) Double: 15 or 17 Dim valueText As String = GetValueStringCore(literal, isSingle, "R", value) ' Floating point values might be represented either in fixed point notation or scientific/exponent notation. ' MSDN comment for Standard Numeric Format Strings used in Single.ToString(String) API (or Double.ToString(String)): ' Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and ' less than the precision specifier; otherwise, scientific notation is used. ' ' However, Dev11 pretty lister differs from this for floating point values with exponent < 0. ' Instead of "greater than -5" mentioned above, it uses fixed point notation as long as exponent is greater than "-(precision + 2)". ' For example, consider pretty listing for Single literals: ' (i) Precision = 7 ' 0.0000001234567F => 0.0000001234567F (exponent = -7: fixed point notation) ' 0.00000001234567F => 0.00000001234567F (exponent = -8: fixed point notation) ' 0.000000001234567F => 1.234567E-9F (exponent = -9: exponent notation) ' 0.0000000001234567F => 1.234567E-10F (exponent = -10: exponent notation) ' (ii) Precision = 9 ' 0.0000000012345678F => 0.00000000123456778F (exponent = -9: fixed point notation) ' 0.00000000012345678F => 0.000000000123456786F (exponent = -10: fixed point notation) ' 0.000000000012345678F => 1.23456783E-11F (exponent = -11: exponent notation) ' 0.0000000000012345678F => 1.23456779E-12F (exponent = -12: exponent notation) ' ' We replicate the same behavior below Dim exponentIndex As Integer = valueText.IndexOf("E"c) If exponentIndex > 0 Then Dim exponent = Integer.Parse(valueText.Substring(exponentIndex + 1), CultureInfo.InvariantCulture) If exponent < 0 Then Dim defaultPrecision As Integer = If(isSingle, 7, 15) Dim numSignificantDigits = exponentIndex - 1 ' subtract 1 for the decimal point Dim actualPrecision As Integer = If(numSignificantDigits > defaultPrecision, defaultPrecision + 2, defaultPrecision) If exponent > -(actualPrecision + 2) Then ' Convert valueText to floating point notation. ' Prepend "0.00000.." Dim prefix = "0." + New String("0"c, -exponent - 1) ' Get the significant digits string. Dim significantDigitsStr = valueText.Substring(0, exponentIndex) ' Remove the existing decimal point, if any, from valueText. If significantDigitsStr.Length > 1 AndAlso significantDigitsStr(1) = "."c Then significantDigitsStr = significantDigitsStr.Remove(1, 1) End If Return prefix + significantDigitsStr End If End If End If ' Single.ToString(String) might return result in exponential notation, where the exponent is formatted to at least 2 digits. ' Dev11 pretty lister is identical in all cases except when the exponent is exactly 2 digit with a leading zero, e.g. "2.3E+08F" or "2.3E-08F". ' Dev11 pretty lists these cases to "2.3E+8F" or "2.3E-8F" respectively; we do the same here. If isSingle Then ' Check if valueText ends with "E+XX" or "E-XX" If valueText.Length > 4 Then If valueText.Length = exponentIndex + 4 Then ' Trim zero for these two cases: "E+0X" or "E-0X" If valueText(exponentIndex + 2) = "0"c Then valueText = valueText.Remove(exponentIndex + 2, 1) End If End If End If End If ' If the value is integral, then append ".0" to the valueText. If Not valueText.Contains("."c) Then Return If(exponentIndex > 0, valueText.Insert(exponentIndex, ".0"), valueText + ".0") End If Return valueText End Function Private Shared Function GetValueStringCore(literal As SyntaxToken, isSingle As Boolean, formatSpecifier As String, <Out> ByRef value As Double) As String If isSingle Then Dim singleValue = DirectCast(literal.Value, Single) value = singleValue Return singleValue.ToString(formatSpecifier, CultureInfo.InvariantCulture) Else value = DirectCast(literal.Value, Double) Return value.ToString(formatSpecifier, CultureInfo.InvariantCulture) End If End Function Private Shared Function GetDecimalLiteralValueString(value As Decimal) As String ' CONSIDER: If the parsed value is integral, i.e. has no decimal point, we should insert ".0" before "D" in the valueText (similar to the pretty listing for float literals). ' CONSIDER: However, native VB compiler doesn't do so for decimal literals, we will maintain compatibility. ' CONSIDER: We may want to consider taking a breaking change and make this consistent between float and decimal literals. Dim valueText = value.ToString(CultureInfo.InvariantCulture) ' Trim any redundant zeros after the decimal point. ' If all the digits after the decimal point are 0, then trim the decimal point as well. Dim parts As String() = valueText.Split("."c) If parts.Length() > 1 Then ' We might have something like "1.000E+100". Ensure we only truncate the zeros before "E". Dim partsAfterDot = parts(1).Split("E"c) Dim stringToTruncate As String = partsAfterDot(0) Dim truncatedString = stringToTruncate.TrimEnd("0"c) If Not String.Equals(truncatedString, stringToTruncate, StringComparison.Ordinal) Then Dim integralPart As String = parts(0) Dim fractionPartOpt As String = If(truncatedString.Length > 0, "." + truncatedString, "") Dim exponentPartOpt As String = If(partsAfterDot.Length > 1, "E" + partsAfterDot(1), "") Return integralPart + fractionPartOpt + exponentPartOpt End If End If Return valueText End Function Private Shared Function GetIntegerLiteralValueString(value As Object, base As LiteralBase) As String Select Case base Case LiteralBase.Decimal Return CType(value, ULong).ToString(CultureInfo.InvariantCulture) Case LiteralBase.Hexadecimal Return "&H" + ConvertToULong(value).ToString("X") Case LiteralBase.Octal Dim val1 As ULong = ConvertToULong(value) Return "&O" + ConvertToOctalString(val1) Case LiteralBase.Binary Dim asLong = CType(ConvertToULong(value), Long) Return "&B" + Convert.ToString(asLong, 2) Case Else Throw ExceptionUtilities.UnexpectedValue(base) End Select End Function Private Shared Function CreateLiteralToken(token As SyntaxToken, newValueString As String, newValue As Object) As SyntaxToken ' create a new token with valid token text and carries over annotations attached to original token to be a good citizen ' it might be replacing a token that has annotation injected by other code cleanups Dim leading = If(token.LeadingTrivia.Count > 0, token.LeadingTrivia, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)) Dim trailing = If(token.TrailingTrivia.Count > 0, token.TrailingTrivia, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)) Select Case token.Kind Case SyntaxKind.FloatingLiteralToken Return token.CopyAnnotationsTo(SyntaxFactory.FloatingLiteralToken(leading, newValueString, token.GetTypeCharacter(), DirectCast(newValue, Double), trailing)) Case SyntaxKind.DecimalLiteralToken Return token.CopyAnnotationsTo(SyntaxFactory.DecimalLiteralToken(leading, newValueString, token.GetTypeCharacter(), DirectCast(newValue, Decimal), trailing)) Case SyntaxKind.IntegerLiteralToken Return token.CopyAnnotationsTo(SyntaxFactory.IntegerLiteralToken(leading, newValueString, token.GetBase().Value, token.GetTypeCharacter(), DirectCast(newValue, ULong), trailing)) Case Else Throw ExceptionUtilities.UnexpectedValue(token.Kind) End Select End Function Private Shared Function ConvertToOctalString(value As ULong) As String Dim exponent As ULong = value Dim builder As New StringBuilder() If value = 0 Then Return "0" End If While (exponent > 0) Dim remainder = exponent Mod 8UL builder.Insert(0, remainder) exponent = exponent \ 8UL End While Return builder.ToString() End Function Private Shared Function HasOverflow(diagnostics As IEnumerable(Of Diagnostic)) As Boolean Return diagnostics.Any(Function(diagnostic As Diagnostic) diagnostic.Id = "BC30036") End Function Private Shared Function ConvertToULong(value As Object) As ULong 'Cannot convert directly to ULong from Short or Integer as negative numbers 'appear to have all bits above the current bit range set to 1 'so short value -32768 or binary 1000000000000000 becomes 'binary 1111111111111111111111111111111111111111111111111000000000000000 'or in decimal 18446744073709518848 'This will cause the subsequent conversion to a hex or octal string to output an incorrect value If TypeOf (value) Is Short Then Return CType(value, UShort) ElseIf TypeOf (value) Is Integer Then Return CType(value, UInteger) Else Return CType(value, ULong) End If End Function End Class 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.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers <ExportCodeCleanupProvider(PredefinedCodeCleanupProviderNames.ReduceTokens, LanguageNames.VisualBasic), [Shared]> <ExtensionOrder(After:=PredefinedCodeCleanupProviderNames.AddMissingTokens, Before:=PredefinedCodeCleanupProviderNames.Format)> Friend Class ReduceTokensCodeCleanupProvider Inherits AbstractTokensCodeCleanupProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="https://github.com/dotnet/roslyn/issues/42820")> Public Sub New() End Sub Public Overrides ReadOnly Property Name As String Get Return PredefinedCodeCleanupProviderNames.ReduceTokens End Get End Property Protected Overrides Function GetRewriterAsync(document As Document, root As SyntaxNode, spans As ImmutableArray(Of TextSpan), workspace As Workspace, cancellationToken As CancellationToken) As Task(Of Rewriter) Return Task.FromResult(Of Rewriter)(New ReduceTokensRewriter(spans, cancellationToken)) End Function Private Class ReduceTokensRewriter Inherits AbstractTokensCodeCleanupProvider.Rewriter Public Sub New(spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken) MyBase.New(spans, cancellationToken) End Sub Public Overrides Function VisitLiteralExpression(node As LiteralExpressionSyntax) As SyntaxNode Dim newNode = DirectCast(MyBase.VisitLiteralExpression(node), LiteralExpressionSyntax) Dim literal As SyntaxToken = newNode.Token Const digitSeparator = "_"c ' Pretty list floating and decimal literals. Select Case literal.Kind Case SyntaxKind.FloatingLiteralToken ' Get the literal identifier text which needs to be pretty listed. Dim idText = literal.GetIdentifierText() ' Compiler has parsed the literal text as single/double value, fetch the string representation of this value. Dim value As Double = 0 Dim valueText As String = GetFloatLiteralValueString(literal, value) + GetTypeCharString(literal.GetTypeCharacter()) If value = 0 OrElse idText.Contains(digitSeparator) Then ' Overflow/underflow case or zero literal, skip pretty listing. Return newNode End If ' If the string representation of the value differs from the identifier text, create a new literal token with same value but pretty listed "valueText". If Not CaseInsensitiveComparison.Equals(valueText, idText) Then Return newNode.ReplaceToken(literal, CreateLiteralToken(literal, valueText, value)) End If Case SyntaxKind.DecimalLiteralToken ' Get the literal identifier text which needs to be pretty listed. Dim idText = literal.GetIdentifierText() Dim value = DirectCast(literal.Value, Decimal) If value = 0 OrElse idText.Contains(digitSeparator) Then ' Overflow/underflow case or zero literal, skip pretty listing. Return newNode End If ' Compiler has parsed the literal text as a decimal value, fetch the string representation of this value. Dim valueText As String = GetDecimalLiteralValueString(value) + GetTypeCharString(literal.GetTypeCharacter()) If Not CaseInsensitiveComparison.Equals(valueText, idText) Then Return newNode.ReplaceToken(literal, CreateLiteralToken(literal, valueText, value)) End If Case SyntaxKind.IntegerLiteralToken ' Get the literal identifier text which needs to be pretty listed. Dim idText = literal.GetIdentifierText() 'The value will only ever be negative when we have a hex or oct value 'it's safe to cast to ULong as we check for negative values later Dim value As ULong = CType(literal.Value, ULong) If value = 0 AndAlso HasOverflow(literal.GetDiagnostics()) Then 'Overflow/underflow, skip pretty listing. Return newNode End If Dim base = literal.GetBase() If Not base.HasValue OrElse idText.Contains(digitSeparator) Then Return newNode End If 'fetch the string representation of this value in the correct base. Dim valueText As String = GetIntegerLiteralValueString(literal.Value, base.Value) + GetTypeCharString(literal.GetTypeCharacter()) If Not CaseInsensitiveComparison.Equals(valueText, idText) Then Return newNode.ReplaceToken(literal, CreateLiteralToken(literal, valueText, value)) End If End Select Return newNode End Function Private Shared Function GetTypeCharString(typeChar As TypeCharacter) As String Select Case typeChar Case TypeCharacter.Single Return "!" Case TypeCharacter.SingleLiteral Return "F" Case TypeCharacter.Double Return "#" Case TypeCharacter.DoubleLiteral Return "R" Case TypeCharacter.Decimal Return "@" Case TypeCharacter.DecimalLiteral Return "D" Case TypeCharacter.Integer Return "%" Case TypeCharacter.IntegerLiteral Return "I" Case TypeCharacter.ShortLiteral Return "S" Case TypeCharacter.Long Return "&" Case TypeCharacter.LongLiteral Return "L" Case TypeCharacter.UIntegerLiteral Return "UI" Case TypeCharacter.UShortLiteral Return "US" Case TypeCharacter.ULongLiteral Return "UL" Case Else Return "" End Select End Function Private Shared Function GetFloatLiteralValueString(literal As SyntaxToken, <Out> ByRef value As Double) As String Dim isSingle As Boolean = literal.GetTypeCharacter() = TypeCharacter.Single OrElse literal.GetTypeCharacter() = TypeCharacter.SingleLiteral ' Get the string representation of the value using The Round-trip ("R") Format Specifier. ' MSDN comments about "R" format specifier: ' The round-trip ("R") format specifier guarantees that a numeric value that is converted to a string will be parsed back into the same numeric value. ' This format is supported only for the Single, Double, and BigInteger types. ' When a Single or Double value is formatted using this specifier, it is first tested using the general format, with 15 digits of precision for a Double and ' 7 digits of precision for a Single. If the value is successfully parsed back to the same numeric value, it is formatted using the general format specifier. ' If the value is not successfully parsed back to the same numeric value, it is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single. ' Hence the possible actual precision values are: ' (a) Single: 7 or 9 and ' (b) Double: 15 or 17 Dim valueText As String = GetValueStringCore(literal, isSingle, "R", value) ' Floating point values might be represented either in fixed point notation or scientific/exponent notation. ' MSDN comment for Standard Numeric Format Strings used in Single.ToString(String) API (or Double.ToString(String)): ' Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and ' less than the precision specifier; otherwise, scientific notation is used. ' ' However, Dev11 pretty lister differs from this for floating point values with exponent < 0. ' Instead of "greater than -5" mentioned above, it uses fixed point notation as long as exponent is greater than "-(precision + 2)". ' For example, consider pretty listing for Single literals: ' (i) Precision = 7 ' 0.0000001234567F => 0.0000001234567F (exponent = -7: fixed point notation) ' 0.00000001234567F => 0.00000001234567F (exponent = -8: fixed point notation) ' 0.000000001234567F => 1.234567E-9F (exponent = -9: exponent notation) ' 0.0000000001234567F => 1.234567E-10F (exponent = -10: exponent notation) ' (ii) Precision = 9 ' 0.0000000012345678F => 0.00000000123456778F (exponent = -9: fixed point notation) ' 0.00000000012345678F => 0.000000000123456786F (exponent = -10: fixed point notation) ' 0.000000000012345678F => 1.23456783E-11F (exponent = -11: exponent notation) ' 0.0000000000012345678F => 1.23456779E-12F (exponent = -12: exponent notation) ' ' We replicate the same behavior below Dim exponentIndex As Integer = valueText.IndexOf("E"c) If exponentIndex > 0 Then Dim exponent = Integer.Parse(valueText.Substring(exponentIndex + 1), CultureInfo.InvariantCulture) If exponent < 0 Then Dim defaultPrecision As Integer = If(isSingle, 7, 15) Dim numSignificantDigits = exponentIndex - 1 ' subtract 1 for the decimal point Dim actualPrecision As Integer = If(numSignificantDigits > defaultPrecision, defaultPrecision + 2, defaultPrecision) If exponent > -(actualPrecision + 2) Then ' Convert valueText to floating point notation. ' Prepend "0.00000.." Dim prefix = "0." + New String("0"c, -exponent - 1) ' Get the significant digits string. Dim significantDigitsStr = valueText.Substring(0, exponentIndex) ' Remove the existing decimal point, if any, from valueText. If significantDigitsStr.Length > 1 AndAlso significantDigitsStr(1) = "."c Then significantDigitsStr = significantDigitsStr.Remove(1, 1) End If Return prefix + significantDigitsStr End If End If End If ' Single.ToString(String) might return result in exponential notation, where the exponent is formatted to at least 2 digits. ' Dev11 pretty lister is identical in all cases except when the exponent is exactly 2 digit with a leading zero, e.g. "2.3E+08F" or "2.3E-08F". ' Dev11 pretty lists these cases to "2.3E+8F" or "2.3E-8F" respectively; we do the same here. If isSingle Then ' Check if valueText ends with "E+XX" or "E-XX" If valueText.Length > 4 Then If valueText.Length = exponentIndex + 4 Then ' Trim zero for these two cases: "E+0X" or "E-0X" If valueText(exponentIndex + 2) = "0"c Then valueText = valueText.Remove(exponentIndex + 2, 1) End If End If End If End If ' If the value is integral, then append ".0" to the valueText. If Not valueText.Contains("."c) Then Return If(exponentIndex > 0, valueText.Insert(exponentIndex, ".0"), valueText + ".0") End If Return valueText End Function Private Shared Function GetValueStringCore(literal As SyntaxToken, isSingle As Boolean, formatSpecifier As String, <Out> ByRef value As Double) As String If isSingle Then Dim singleValue = DirectCast(literal.Value, Single) value = singleValue Return singleValue.ToString(formatSpecifier, CultureInfo.InvariantCulture) Else value = DirectCast(literal.Value, Double) Return value.ToString(formatSpecifier, CultureInfo.InvariantCulture) End If End Function Private Shared Function GetDecimalLiteralValueString(value As Decimal) As String ' CONSIDER: If the parsed value is integral, i.e. has no decimal point, we should insert ".0" before "D" in the valueText (similar to the pretty listing for float literals). ' CONSIDER: However, native VB compiler doesn't do so for decimal literals, we will maintain compatibility. ' CONSIDER: We may want to consider taking a breaking change and make this consistent between float and decimal literals. Dim valueText = value.ToString(CultureInfo.InvariantCulture) ' Trim any redundant zeros after the decimal point. ' If all the digits after the decimal point are 0, then trim the decimal point as well. Dim parts As String() = valueText.Split("."c) If parts.Length() > 1 Then ' We might have something like "1.000E+100". Ensure we only truncate the zeros before "E". Dim partsAfterDot = parts(1).Split("E"c) Dim stringToTruncate As String = partsAfterDot(0) Dim truncatedString = stringToTruncate.TrimEnd("0"c) If Not String.Equals(truncatedString, stringToTruncate, StringComparison.Ordinal) Then Dim integralPart As String = parts(0) Dim fractionPartOpt As String = If(truncatedString.Length > 0, "." + truncatedString, "") Dim exponentPartOpt As String = If(partsAfterDot.Length > 1, "E" + partsAfterDot(1), "") Return integralPart + fractionPartOpt + exponentPartOpt End If End If Return valueText End Function Private Shared Function GetIntegerLiteralValueString(value As Object, base As LiteralBase) As String Select Case base Case LiteralBase.Decimal Return CType(value, ULong).ToString(CultureInfo.InvariantCulture) Case LiteralBase.Hexadecimal Return "&H" + ConvertToULong(value).ToString("X") Case LiteralBase.Octal Dim val1 As ULong = ConvertToULong(value) Return "&O" + ConvertToOctalString(val1) Case LiteralBase.Binary Dim asLong = CType(ConvertToULong(value), Long) Return "&B" + Convert.ToString(asLong, 2) Case Else Throw ExceptionUtilities.UnexpectedValue(base) End Select End Function Private Shared Function CreateLiteralToken(token As SyntaxToken, newValueString As String, newValue As Object) As SyntaxToken ' create a new token with valid token text and carries over annotations attached to original token to be a good citizen ' it might be replacing a token that has annotation injected by other code cleanups Dim leading = If(token.LeadingTrivia.Count > 0, token.LeadingTrivia, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)) Dim trailing = If(token.TrailingTrivia.Count > 0, token.TrailingTrivia, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)) Select Case token.Kind Case SyntaxKind.FloatingLiteralToken Return token.CopyAnnotationsTo(SyntaxFactory.FloatingLiteralToken(leading, newValueString, token.GetTypeCharacter(), DirectCast(newValue, Double), trailing)) Case SyntaxKind.DecimalLiteralToken Return token.CopyAnnotationsTo(SyntaxFactory.DecimalLiteralToken(leading, newValueString, token.GetTypeCharacter(), DirectCast(newValue, Decimal), trailing)) Case SyntaxKind.IntegerLiteralToken Return token.CopyAnnotationsTo(SyntaxFactory.IntegerLiteralToken(leading, newValueString, token.GetBase().Value, token.GetTypeCharacter(), DirectCast(newValue, ULong), trailing)) Case Else Throw ExceptionUtilities.UnexpectedValue(token.Kind) End Select End Function Private Shared Function ConvertToOctalString(value As ULong) As String Dim exponent As ULong = value Dim builder As New StringBuilder() If value = 0 Then Return "0" End If While (exponent > 0) Dim remainder = exponent Mod 8UL builder.Insert(0, remainder) exponent = exponent \ 8UL End While Return builder.ToString() End Function Private Shared Function HasOverflow(diagnostics As IEnumerable(Of Diagnostic)) As Boolean Return diagnostics.Any(Function(diagnostic As Diagnostic) diagnostic.Id = "BC30036") End Function Private Shared Function ConvertToULong(value As Object) As ULong 'Cannot convert directly to ULong from Short or Integer as negative numbers 'appear to have all bits above the current bit range set to 1 'so short value -32768 or binary 1000000000000000 becomes 'binary 1111111111111111111111111111111111111111111111111000000000000000 'or in decimal 18446744073709518848 'This will cause the subsequent conversion to a hex or octal string to output an incorrect value If TypeOf (value) Is Short Then Return CType(value, UShort) ElseIf TypeOf (value) Is Integer Then Return CType(value, UInteger) Else Return CType(value, ULong) End If End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CancellableLazy.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; namespace Roslyn.Utilities { internal static class CancellableLazy { public static CancellableLazy<T> Create<T>(T value) => new(value); public static CancellableLazy<T> Create<T>(Func<CancellationToken, T> valueFactory) => new(valueFactory); } }
// 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; namespace Roslyn.Utilities { internal static class CancellableLazy { public static CancellableLazy<T> Create<T>(T value) => new(value); public static CancellableLazy<T> Create<T>(Func<CancellationToken, T> valueFactory) => new(valueFactory); } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/CSharp/Portable/Symbols/SymbolVisitor`1.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.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CSharpSymbolVisitor<TResult> { public virtual TResult Visit(Symbol symbol) { return (object)symbol == null ? default(TResult) : symbol.Accept(this); } public virtual TResult DefaultVisit(Symbol symbol) { return default(TResult); } public virtual TResult VisitAlias(AliasSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitArrayType(ArrayTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitAssembly(AssemblySymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitDynamicType(DynamicTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitDiscard(DiscardSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitEvent(EventSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitField(FieldSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitLabel(LabelSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitLocal(LocalSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitMethod(MethodSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitModule(ModuleSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitNamedType(NamedTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitNamespace(NamespaceSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitParameter(ParameterSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitPointerType(PointerTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitProperty(PropertySymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitRangeVariable(RangeVariableSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitTypeParameter(TypeParameterSymbol symbol) { return DefaultVisit(symbol); } } }
// 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.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CSharpSymbolVisitor<TResult> { public virtual TResult Visit(Symbol symbol) { return (object)symbol == null ? default(TResult) : symbol.Accept(this); } public virtual TResult DefaultVisit(Symbol symbol) { return default(TResult); } public virtual TResult VisitAlias(AliasSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitArrayType(ArrayTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitAssembly(AssemblySymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitDynamicType(DynamicTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitDiscard(DiscardSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitEvent(EventSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitField(FieldSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitLabel(LabelSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitLocal(LocalSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitMethod(MethodSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitModule(ModuleSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitNamedType(NamedTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitNamespace(NamespaceSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitParameter(ParameterSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitPointerType(PointerTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitProperty(PropertySymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitRangeVariable(RangeVariableSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitTypeParameter(TypeParameterSymbol symbol) { return DefaultVisit(symbol); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Portable/SymbolDisplay/SymbolDisplayVisitor_Constants.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.Reflection Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class SymbolDisplayVisitor Protected Overrides Sub AddBitwiseOr() AddKeyword(SyntaxKind.OrKeyword) End Sub Protected Overrides Sub AddExplicitlyCastedLiteralValue(namedType As INamedTypeSymbol, type As SpecialType, value As Object) ' VB doesn't actually need to cast a literal value to get an enum value. So we just add ' the literal value directly. AddLiteralValue(type, value) End Sub Protected Overrides Sub AddLiteralValue(type As SpecialType, value As Object) Debug.Assert(value.GetType().GetTypeInfo().IsPrimitive OrElse TypeOf value Is String OrElse TypeOf value Is Decimal OrElse TypeOf value Is DateTime) Select Case type Case SpecialType.System_String SymbolDisplay.AddSymbolDisplayParts(builder, DirectCast(value, String)) Case SpecialType.System_Char SymbolDisplay.AddSymbolDisplayParts(builder, DirectCast(value, Char)) Case Else Dim valueString = SymbolDisplay.FormatPrimitive(value, quoteStrings:=True, useHexadecimalNumbers:=False) Me.builder.Add(CreatePart(SymbolDisplayPartKind.NumericLiteral, Nothing, valueString, False)) End Select End Sub ''' <summary> Append a default argument (i.e. the default argument of an optional parameter). ''' Assumed to be non-null. ''' </summary> Private Sub AddConstantValue(type As ITypeSymbol, constantValue As Object, Optional preferNumericValueOrExpandedFlagsForEnum As Boolean = False) If constantValue IsNot Nothing Then AddNonNullConstantValue(type, constantValue, preferNumericValueOrExpandedFlagsForEnum) Else AddKeyword(SyntaxKind.NothingKeyword) End If 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.Reflection Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class SymbolDisplayVisitor Protected Overrides Sub AddBitwiseOr() AddKeyword(SyntaxKind.OrKeyword) End Sub Protected Overrides Sub AddExplicitlyCastedLiteralValue(namedType As INamedTypeSymbol, type As SpecialType, value As Object) ' VB doesn't actually need to cast a literal value to get an enum value. So we just add ' the literal value directly. AddLiteralValue(type, value) End Sub Protected Overrides Sub AddLiteralValue(type As SpecialType, value As Object) Debug.Assert(value.GetType().GetTypeInfo().IsPrimitive OrElse TypeOf value Is String OrElse TypeOf value Is Decimal OrElse TypeOf value Is DateTime) Select Case type Case SpecialType.System_String SymbolDisplay.AddSymbolDisplayParts(builder, DirectCast(value, String)) Case SpecialType.System_Char SymbolDisplay.AddSymbolDisplayParts(builder, DirectCast(value, Char)) Case Else Dim valueString = SymbolDisplay.FormatPrimitive(value, quoteStrings:=True, useHexadecimalNumbers:=False) Me.builder.Add(CreatePart(SymbolDisplayPartKind.NumericLiteral, Nothing, valueString, False)) End Select End Sub ''' <summary> Append a default argument (i.e. the default argument of an optional parameter). ''' Assumed to be non-null. ''' </summary> Private Sub AddConstantValue(type As ITypeSymbol, constantValue As Object, Optional preferNumericValueOrExpandedFlagsForEnum As Boolean = False) If constantValue IsNot Nothing Then AddNonNullConstantValue(type, constantValue, preferNumericValueOrExpandedFlagsForEnum) Else AddKeyword(SyntaxKind.NothingKeyword) End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/CSharp/Test/Symbol/Symbols/IndexerTests.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class IndexerTests : CSharpTestBase { [ClrOnlyFact] public void Indexers() { var source = @"using System.Runtime.CompilerServices; class C { [IndexerName(""P"")] internal string this[string index] { get { return null; } set { } } } interface I { object this[int i, params object[] args] { set; } } struct S { internal object this[string x] { get { return null; } } }"; Action<ModuleSymbol> validator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); CheckIndexer(type.Indexers.Single(), true, true, SpecialType.System_String, SpecialType.System_String); type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I"); CheckIndexer(type.Indexers.Single(), false, true, SpecialType.System_Object, SpecialType.System_Int32, SpecialType.None); type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("S"); CheckIndexer(type.Indexers.Single(), true, false, SpecialType.System_Object, SpecialType.System_String); }; CompileAndVerify( source: source, sourceSymbolValidator: validator, symbolValidator: validator, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); } [ClrOnlyFact] public void InterfaceImplementations() { var source = @"using System.Runtime.CompilerServices; interface IA { object this[string index] { get; set; } } interface IB { object this[string index] { get; } } interface IC { [IndexerName(""P"")] object this[string index] { get; set; } } class A : IA, IB, IC { object IA.this[string index] { get { return null; } set { } } object IB.this[string index] { get { return null; } } object IC.this[string index] { get { return null; } set { } } } class B : IA, IB, IC { public object this[string index] { get { return null; } set { } } } class C : IB, IC { [IndexerName(""Q"")] public object this[string index] { get { return null; } set { } } }"; var compilation = CompileAndVerify(source); compilation.VerifyDiagnostics(); var globalNamespace = (NamespaceSymbol)((CSharpCompilation)compilation.Compilation).GlobalNamespace; var type = globalNamespace.GetMember<NamedTypeSymbol>("IA"); CheckIndexer(type.Indexers.Single(), true, true, SpecialType.System_Object, SpecialType.System_String); type = globalNamespace.GetMember<NamedTypeSymbol>("IB"); CheckIndexer(type.Indexers.Single(), true, false, SpecialType.System_Object, SpecialType.System_String); type = globalNamespace.GetMember<NamedTypeSymbol>("IC"); CheckIndexer(type.Indexers.Single(), true, true, SpecialType.System_Object, SpecialType.System_String); type = globalNamespace.GetMember<NamedTypeSymbol>("A"); var typeAProperties = type.GetMembers().Where(m => m.Kind == SymbolKind.Property).Cast<PropertySymbol>().ToArray(); Assert.Equal(3, typeAProperties.Length); CheckIndexer(typeAProperties[0], true, true, SpecialType.System_Object, SpecialType.System_String); CheckIndexer(typeAProperties[1], true, false, SpecialType.System_Object, SpecialType.System_String); CheckIndexer(typeAProperties[2], true, true, SpecialType.System_Object, SpecialType.System_String); var sourceType = globalNamespace.GetMember<SourceNamedTypeSymbol>("B"); CheckIndexer(sourceType.Indexers.Single(), true, true, SpecialType.System_Object, SpecialType.System_String); var bridgeMethods = sourceType.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods; Assert.Equal(2, bridgeMethods.Length); Assert.True(bridgeMethods.Select(GetPairForSynthesizedExplicitImplementation).SetEquals(new[] { new KeyValuePair<string, string>("System.Object IC.this[System.String index].get", "System.Object B.this[System.String index].get"), new KeyValuePair<string, string>("void IC.this[System.String index].set", "void B.this[System.String index].set"), })); sourceType = globalNamespace.GetMember<SourceNamedTypeSymbol>("C"); CheckIndexer(sourceType.Indexers.Single(), true, true, SpecialType.System_Object, SpecialType.System_String); bridgeMethods = sourceType.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods; Assert.Equal(3, bridgeMethods.Length); Assert.True(bridgeMethods.Select(GetPairForSynthesizedExplicitImplementation).SetEquals(new[] { new KeyValuePair<string, string>("System.Object IB.this[System.String index].get", "System.Object C.this[System.String index].get"), new KeyValuePair<string, string>("System.Object IC.this[System.String index].get", "System.Object C.this[System.String index].get"), new KeyValuePair<string, string>("void IC.this[System.String index].set", "void C.this[System.String index].set"), })); } private static KeyValuePair<string, string> GetPairForSynthesizedExplicitImplementation(SynthesizedExplicitImplementationForwardingMethod bridge) { return new KeyValuePair<string, string>(bridge.ExplicitInterfaceImplementations.Single().ToTestDisplayString(), bridge.ImplementingMethod.ToTestDisplayString()); } private static void CheckIndexer(PropertySymbol property, bool hasGet, bool hasSet, SpecialType expectedType, params SpecialType[] expectedParameterTypes) { Assert.NotNull(property); Assert.True(property.IsIndexer); Assert.Equal(property.Type.SpecialType, expectedType); CheckParameters(property.Parameters, expectedParameterTypes); var getter = property.GetMethod; if (hasGet) { Assert.NotNull(getter); Assert.Equal(getter.ReturnType.SpecialType, expectedType); CheckParameters(getter.Parameters, expectedParameterTypes); } else { Assert.Null(getter); } var setter = property.SetMethod; if (hasSet) { Assert.NotNull(setter); Assert.True(setter.ReturnsVoid); CheckParameters(setter.Parameters, expectedParameterTypes.Concat(new[] { expectedType }).ToArray()); } else { Assert.Null(setter); } Assert.Equal(property.GetMethod != null, hasGet); Assert.Equal(property.SetMethod != null, hasSet); } private static void CheckParameters(ImmutableArray<ParameterSymbol> parameters, SpecialType[] expectedTypes) { Assert.Equal(parameters.Length, expectedTypes.Length); for (int i = 0; i < expectedTypes.Length; i++) { var parameter = parameters[i]; Assert.Equal(parameter.Ordinal, i); Assert.Equal(parameter.Type.SpecialType, expectedTypes[i]); } } [Fact] public void OverloadResolution() { var source = @"class C { int this[int x, int y] { get { return 0; } } int F(C c) { return this[0] + c[0, c] + c[1, 2, 3]; } }"; CreateCompilation(source).VerifyDiagnostics( // (9,16): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'C.this[int, int]' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "this[0]").WithArguments("y", "C.this[int, int]").WithLocation(9, 16), // (10,18): error CS1503: Argument 2: cannot convert from 'C' to 'int' Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("2", "C", "int").WithLocation(10, 18), // (11,13): error CS1501: No overload for method 'this' takes 3 arguments Diagnostic(ErrorCode.ERR_BadArgCount, "c[1, 2, 3]").WithArguments("this", "3").WithLocation(11, 13)); } [Fact] public void OverridingHiddenIndexer() { var source = @" using System.Runtime.CompilerServices; public class A { public virtual int this[int x] { get { return 0; } } } public class B : A { // Even though the user has specified a name for this indexer that // doesn't match the name of the base class accessor, we expect // it to hide A's indexer in subclasses (i.e. C). [IndexerName(""NotItem"")] public int this[int x] { get { return 0; } } //NB: not virtual } public class C : B { public override int this[int x] { get { return 0; } } }"; var compilation = CreateCompilation(source); // NOTE: we could eliminate WRN_NewOrOverrideExpected by putting a "new" modifier on B.this[] compilation.VerifyDiagnostics( // (15,16): warning CS0114: 'B.this[int]' hides inherited member 'A.this[int]'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "this").WithArguments("B.this[int]", "A.this[int]"), // (20,25): error CS0506: 'C.this[int]': cannot override inherited member 'B.this[int]' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "this").WithArguments("C.this[int]", "B.this[int]")); var classC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var indexerC = classC.Indexers.Single(); Assert.Null(indexerC.OverriddenProperty); Assert.Null(indexerC.GetMethod.OverriddenMethod); } [Fact] public void ImplicitlyImplementingIndexersWithDifferentNames_DifferentInterfaces_Source() { var text = @" using System.Runtime.CompilerServices; interface I1 { [IndexerName(""A"")] int this[int x] { get; } } interface I2 { [IndexerName(""B"")] int this[int x] { get; } } class C : I1, I2 { public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics(); var interface1 = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I1"); var interface1Indexer = interface1.Indexers.Single(); var interface2 = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I2"); var interface2Indexer = interface2.Indexers.Single(); var @class = compilation.GlobalNamespace.GetMember<SourceNamedTypeSymbol>("C"); var classIndexer = @class.Indexers.Single(); // All of the indexers have the same Name Assert.Equal(WellKnownMemberNames.Indexer, classIndexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, interface1Indexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, interface2Indexer.Name); // All of the indexers have different MetadataNames Assert.NotEqual(interface1Indexer.MetadataName, interface2Indexer.MetadataName); Assert.NotEqual(interface1Indexer.MetadataName, classIndexer.MetadataName); Assert.NotEqual(interface2Indexer.MetadataName, classIndexer.MetadataName); // classIndexer implements both Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interface1Indexer)); Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interface2Indexer)); var synthesizedExplicitImplementations = @class.GetSynthesizedExplicitImplementations(default(CancellationToken)).ForwardingMethods; Assert.Equal(2, synthesizedExplicitImplementations.Length); Assert.Equal(classIndexer.GetMethod, synthesizedExplicitImplementations[0].ImplementingMethod); Assert.Equal(classIndexer.GetMethod, synthesizedExplicitImplementations[1].ImplementingMethod); var interface1Getter = interface1Indexer.GetMethod; var interface2Getter = interface2Indexer.GetMethod; var interface1GetterImpl = synthesizedExplicitImplementations[0].ExplicitInterfaceImplementations.Single(); var interface2GetterImpl = synthesizedExplicitImplementations[1].ExplicitInterfaceImplementations.Single(); Assert.True(interface1Getter == interface1GetterImpl ^ interface1Getter == interface2GetterImpl); Assert.True(interface2Getter == interface1GetterImpl ^ interface2Getter == interface2GetterImpl); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ImplicitlyImplementingIndexersWithDifferentNames_DifferentInterfaces_Metadata() { var il = @" .class interface public abstract auto ansi I1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('A')} .method public hidebysig newslot specialname abstract virtual instance int32 get_A(int32 x) cil managed { } // end of method I1::get_A .property instance int32 A(int32) { .get instance int32 I1::get_A(int32) } // end of property I1::A } // end of class I1 .class interface public abstract auto ansi I2 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('B')} .method public hidebysig newslot specialname abstract virtual instance int32 get_B(int32 x) cil managed { } // end of method I2::get_B .property instance int32 B(int32) { .get instance int32 I2::get_B(int32) } // end of property I2::B } // end of class I2 "; var csharp = @" class C : I1, I2 { public int this[int x] { get { return 0; } } } "; CompileWithCustomILSource(csharp, il, compilation => { var interface1 = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I1"); var interface1Indexer = interface1.Indexers.Single(); var interface2 = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I2"); var interface2Indexer = interface2.Indexers.Single(); var @class = compilation.GlobalNamespace.GetMember<SourceNamedTypeSymbol>("C"); var classIndexer = @class.Indexers.Single(); // All of the indexers have the same Name Assert.Equal(WellKnownMemberNames.Indexer, classIndexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, interface1Indexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, interface2Indexer.Name); // All of the indexers have different MetadataNames Assert.NotEqual(interface1Indexer.MetadataName, interface2Indexer.MetadataName); Assert.NotEqual(interface1Indexer.MetadataName, classIndexer.MetadataName); Assert.NotEqual(interface2Indexer.MetadataName, classIndexer.MetadataName); // classIndexer implements both Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interface1Indexer)); Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interface2Indexer)); var synthesizedExplicitImplementations = @class.GetSynthesizedExplicitImplementations(default(CancellationToken)).ForwardingMethods; Assert.Equal(2, synthesizedExplicitImplementations.Length); Assert.Equal(classIndexer.GetMethod, synthesizedExplicitImplementations[0].ImplementingMethod); Assert.Equal(classIndexer.GetMethod, synthesizedExplicitImplementations[1].ImplementingMethod); var interface1Getter = interface1Indexer.GetMethod; var interface2Getter = interface2Indexer.GetMethod; var interface1GetterImpl = synthesizedExplicitImplementations[0].ExplicitInterfaceImplementations.Single(); var interface2GetterImpl = synthesizedExplicitImplementations[1].ExplicitInterfaceImplementations.Single(); Assert.True(interface1Getter == interface1GetterImpl ^ interface1Getter == interface2GetterImpl); Assert.True(interface2Getter == interface1GetterImpl ^ interface2Getter == interface2GetterImpl); }); } /// <summary> /// Metadata type has two indexers with the same signature but different names. /// Both are implicitly implemented by a single source indexer. /// </summary> [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ImplicitlyImplementingIndexersWithDifferentNames_SameInterface() { var il = @" .class interface public abstract auto ansi I1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('getter')} .method public hidebysig newslot specialname abstract virtual instance int32 getter(int32 x) cil managed { } // end of method I1::getter .property instance int32 A(int32) { .get instance int32 I1::getter(int32) } // end of property I1::A .property instance int32 B(int32) { .get instance int32 I1::getter(int32) } // end of property I1::B } // end of class I1 "; var csharp = @" class C : I1 { public int this[int x] { get { return 0; } } } "; CompileWithCustomILSource(csharp, il, compilation => { var @interface = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I1"); var interfaceIndexers = @interface.Indexers; Assert.Equal(2, interfaceIndexers.Length); Assert.Equal(interfaceIndexers[0].ToTestDisplayString(), interfaceIndexers[1].ToTestDisplayString()); var @class = compilation.GlobalNamespace.GetMember<SourceNamedTypeSymbol>("C"); var classIndexer = @class.Indexers.Single(); // classIndexer implements both Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interfaceIndexers[0])); Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interfaceIndexers[1])); var synthesizedExplicitImplementation = @class.GetSynthesizedExplicitImplementations(default(CancellationToken)).ForwardingMethods.Single(); Assert.Equal(classIndexer.GetMethod, synthesizedExplicitImplementation.ImplementingMethod); Assert.Equal(interfaceIndexers[0].GetMethod, synthesizedExplicitImplementation.ExplicitInterfaceImplementations.Single()); Assert.Equal(interfaceIndexers[1].GetMethod, synthesizedExplicitImplementation.ExplicitInterfaceImplementations.Single()); }); } /// <summary> /// Metadata type has two indexers with the same signature but different names. /// Both are explicitly implemented by a single source indexer, resulting in an /// ambiguity error. /// </summary> [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void AmbiguousExplicitIndexerImplementation() { // NOTE: could be done in C# using IndexerNameAttribute var il = @" .class interface public abstract auto ansi I1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('get_Item')} .method public hidebysig newslot specialname abstract virtual instance int32 get_Item(int32 x) cil managed { } // end of method I1::get_Item .property instance int32 A(int32) { .get instance int32 I1::get_Item(int32) } // end of property I1::A .property instance int32 B(int32) { .get instance int32 I1::get_Item(int32) } // end of property I1::B } // end of class I1 "; var csharp1 = @" class C : I1 { int I1.this[int x] { get { return 0; } } } "; var compilation = CreateCompilationWithILAndMscorlib40(csharp1, il).VerifyDiagnostics( // (4,12): warning CS0473: Explicit interface implementation 'C.I1.this[int]' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "this").WithArguments("C.I1.this[int]"), // (2,7): error CS0535: 'C' does not implement interface member 'I1.this[int]' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C", "I1.this[int]")); var @interface = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I1"); var interfaceIndexers = @interface.Indexers; Assert.Equal(2, interfaceIndexers.Length); Assert.Equal(interfaceIndexers[0].ToTestDisplayString(), interfaceIndexers[1].ToTestDisplayString()); var @class = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var classIndexer = @class.GetProperty("I1.this[]"); // One is implemented, the other is not (unspecified which) var indexer0Impl = @class.FindImplementationForInterfaceMember(interfaceIndexers[0]); var indexer1Impl = @class.FindImplementationForInterfaceMember(interfaceIndexers[1]); Assert.True(indexer0Impl == classIndexer ^ indexer1Impl == classIndexer); Assert.True(indexer0Impl == null ^ indexer1Impl == null); var csharp2 = @" class C : I1 { public int this[int x] { get { return 0; } } } "; compilation = CreateCompilationWithILAndMscorlib40(csharp2, il).VerifyDiagnostics(); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void HidingIndexerWithDifferentName() { // NOTE: could be done in C# using IndexerNameAttribute var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('A')} .method public hidebysig specialname instance int32 get_A(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 A(int32) { .get instance int32 Base::get_A(int32) } // end of property Base::A } // end of class Base "; var csharp = @" class Derived : Base { public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilationWithILAndMscorlib40(csharp, il); compilation.VerifyDiagnostics( // (4,16): warning CS0108: 'Derived.this[int]' hides inherited member 'Base.this[int]'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "this").WithArguments("Derived.this[int]", "Base.this[int]")); var baseClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseIndexer = baseClass.Indexers.Single(); var derivedClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var derivedIndexer = derivedClass.Indexers.Single(); // The indexers have the same Name Assert.Equal(WellKnownMemberNames.Indexer, derivedIndexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, baseIndexer.Name); // The indexers have different MetadataNames Assert.NotEqual(baseIndexer.MetadataName, derivedIndexer.MetadataName); Assert.Equal(baseIndexer, derivedIndexer.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void OverridingIndexerWithDifferentName() { // NOTE: could be done in C# using IndexerNameAttribute var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('A')} .method public hidebysig newslot specialname virtual instance int32 get_A(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 A(int32) { .get instance int32 Base::get_A(int32) } // end of property Base::A } // end of class Base "; var csharp = @" class Derived : Base { public override int this[int x] { get { return 0; } } } "; CompileWithCustomILSource(csharp, il, compilation => { var baseClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseIndexer = baseClass.Indexers.Single(); var derivedClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var derivedIndexer = derivedClass.Indexers.Single(); // Rhe indexers have the same Name Assert.Equal(WellKnownMemberNames.Indexer, derivedIndexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, baseIndexer.Name); // The indexers have different MetadataNames Assert.NotEqual(baseIndexer.MetadataName, derivedIndexer.MetadataName); Assert.Equal(baseIndexer, derivedIndexer.OverriddenProperty); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void HidingMultipleIndexers() { // NOTE: could be done in C# using IndexerNameAttribute var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('getter')} .method public hidebysig specialname instance int32 getter(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 A(int32) { .get instance int32 Base::getter(int32) } // end of property Base::A .property instance int32 B(int32) { .get instance int32 Base::getter(int32) } // end of property Base::B } // end of class Base "; var csharp = @" class Derived : Base { public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilationWithILAndMscorlib40(csharp, il); // As in dev10, we report only the first hidden member. compilation.VerifyDiagnostics( // (4,16): warning CS0108: 'Derived.this[int]' hides inherited member 'Base.this[int]'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "this").WithArguments("Derived.this[int]", "Base.this[int]")); var baseClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseIndexers = baseClass.Indexers; var derivedClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var derivedIndexer = derivedClass.Indexers.Single(); // The indexers have the same Name Assert.Equal(WellKnownMemberNames.Indexer, derivedIndexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, baseIndexers[0].Name); Assert.Equal(WellKnownMemberNames.Indexer, baseIndexers[1].Name); // The indexers have different MetadataNames Assert.NotEqual(baseIndexers[0].MetadataName, baseIndexers[1].MetadataName); Assert.NotEqual(baseIndexers[0].MetadataName, derivedIndexer.MetadataName); Assert.NotEqual(baseIndexers[1].MetadataName, derivedIndexer.MetadataName); // classIndexer implements both var hiddenMembers = derivedIndexer.OverriddenOrHiddenMembers.HiddenMembers; Assert.Equal(2, hiddenMembers.Length); Assert.Contains(baseIndexers[0], hiddenMembers); Assert.Contains(baseIndexers[1], hiddenMembers); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void OverridingMultipleIndexers() { // NOTE: could be done in C# using IndexerNameAttribute var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('getter')} .method public hidebysig newslot specialname virtual instance int32 getter(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 A(int32) { .get instance int32 Base::getter(int32) } // end of property Base::A .property instance int32 B(int32) { .get instance int32 Base::getter(int32) } // end of property Base::B } // end of class Base "; var csharp = @" class Derived : Base { public override int this[int x] { get { return 0; } } } "; var compilation = CreateCompilationWithILAndMscorlib40(csharp, il).VerifyDiagnostics( // (4,25): error CS0462: The inherited members 'Base.this[int]' and 'Base.this[int]' have the same signature in type 'Derived', so they cannot be overridden Diagnostic(ErrorCode.ERR_AmbigOverride, "this").WithArguments("Base.this[int]", "Base.this[int]", "Derived")); var baseClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseIndexers = baseClass.Indexers; var derivedClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var derivedIndexer = derivedClass.Indexers.Single(); // The indexers have the same Name Assert.Equal(WellKnownMemberNames.Indexer, derivedIndexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, baseIndexers[0].Name); Assert.Equal(WellKnownMemberNames.Indexer, baseIndexers[1].Name); // The indexers have different MetadataNames Assert.NotEqual(baseIndexers[0].MetadataName, baseIndexers[1].MetadataName); Assert.NotEqual(baseIndexers[0].MetadataName, derivedIndexer.MetadataName); Assert.NotEqual(baseIndexers[1].MetadataName, derivedIndexer.MetadataName); // classIndexer implements both var overriddenMembers = derivedIndexer.OverriddenOrHiddenMembers.OverriddenMembers; Assert.Equal(2, overriddenMembers.Length); Assert.Contains(baseIndexers[0], overriddenMembers); Assert.Contains(baseIndexers[1], overriddenMembers); } [Fact] public void IndexerAccessErrors() { var source = @"class C { public int this[int x, long y] { get { return x; } set { } } void M(C c) { c[0] = c[0, 0, 0]; //wrong number of arguments c[true, 1] = c[y: 1, x: long.MaxValue]; //wrong argument types c[1, x: 1] = c[x: 1, 2]; //bad mix of named and positional this[q: 1, r: 2] = base[0]; //bad parameter names / no indexer } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_1).VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'C.this[int, long]' // c[0] = c[0, 0, 0]; //wrong number of arguments Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "c[0]").WithArguments("y", "C.this[int, long]").WithLocation(7, 9), // (7,16): error CS1501: No overload for method 'this' takes 3 arguments // c[0] = c[0, 0, 0]; //wrong number of arguments Diagnostic(ErrorCode.ERR_BadArgCount, "c[0, 0, 0]").WithArguments("this", "3").WithLocation(7, 16), // (8,11): error CS1503: Argument 1: cannot convert from 'bool' to 'int' // c[true, 1] = c[y: 1, x: long.MaxValue]; //wrong argument types Diagnostic(ErrorCode.ERR_BadArgType, "true").WithArguments("1", "bool", "int").WithLocation(8, 11), // (8,33): error CS1503: Argument 2: cannot convert from 'long' to 'int' // c[true, 1] = c[y: 1, x: long.MaxValue]; //wrong argument types Diagnostic(ErrorCode.ERR_BadArgType, "long.MaxValue").WithArguments("2", "long", "int").WithLocation(8, 33), // (9,14): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // c[1, x: 1] = c[x: 1, 2]; //bad mix of named and positional Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(9, 14), // (9,30): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // c[1, x: 1] = c[x: 1, 2]; //bad mix of named and positional Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(9, 30), // (10,14): error CS1739: The best overload for 'this' does not have a parameter named 'q' // this[q: 1, r: 2] = base[0]; //bad parameter names / no indexer Diagnostic(ErrorCode.ERR_BadNamedArgument, "q").WithArguments("this", "q").WithLocation(10, 14), // (10,28): error CS0021: Cannot apply indexing with [] to an expression of type 'object' // this[q: 1, r: 2] = base[0]; //bad parameter names / no indexer Diagnostic(ErrorCode.ERR_BadIndexLHS, "base[0]").WithArguments("object").WithLocation(10, 28) ); } [Fact] public void OverloadResolutionOnIndexersNotAccessors() { var source = @"class C { public int this[int x] { set { } } public int this[int x, double d = 1] { get { return x; } set { } } void M(C c) { int x = c[0]; //pick the first overload, even though it has no getter and the second would work } }"; CreateCompilation(source).VerifyDiagnostics( // (8,17): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "c[0]").WithArguments("C.this[int]")); } [Fact] public void UseExplicitInterfaceImplementationAccessor() { var source = @"interface I { int this[int x] { get; } } class C : I { int I.this[int x] { get { return x; } } void M(C c) { int x = c[0]; // no indexer found int y = ((I)c)[0]; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,17): error CS0021: Cannot apply indexing with [] to an expression of type 'C' Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[0]").WithArguments("C")); } [Fact] public void UsePropertyAndAccessorsDirectly() { var source = @"class C { int this[int x] { get { return x; } set { } } void M(C c) { int x = c.Item[1]; //CS1061 - no such member int y = c.get_Item(1); //CS0571 - use the indexer c.set_Item(y); //CS0571 - use the indexer } }"; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS1061: 'C' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item").WithArguments("C", "Item"), // (8,19): error CS0571: 'C.this[int].get': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("C.this[int].get"), // (9,11): error CS0571: 'C.this[int].set': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Item").WithArguments("C.this[int].set")); } [Fact] public void NestedIndexerAccesses() { var source = @"class C { C this[int x] { get { return this; } set { } } int[] this[char x] { get { return null; } set { } } void M(C c) { int x = c[0][1][2][3]['a'][1]; //fine } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void NamedParameters() { var source = @"class C { int this[int x, string y, char z] { get { return x; } } void M(C c) { int x; x = c[x: 0, y: ""hello"", z:'a']; x = c[0, y: ""hello"", z:'a']; x = c[0, ""hello"", z:'a']; x = c[0, ""hello"", 'a']; x = c[z: 'a', x: 0, y: ""hello""]; //all reordered x = c[0, z:'a', y: ""hello""]; //some reordered } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void OptionalParameters() { var source = @"class C { int this[int x = 1, string y = ""goodbye"", char z = 'b'] { get { return x; } } void M(C c) { int x; x = this[]; //CS0443 - can't omit all x = c[x: 0]; x = c[y: ""hello""]; x = c[z:'a']; x = c[x: 0, y: ""hello""]; x = c[x: 0, z:'a']; x = c[y: ""hello"", z:'a']; x = c[x: 0, y: ""hello"", z:'a']; } }"; CreateCompilation(source).VerifyDiagnostics( // (8,18): error CS0443: Syntax error; value expected Diagnostic(ErrorCode.ERR_ValueExpected, "]")); } [Fact] public void ParameterArray() { var source = @"class C { int this[params int[] args] { get { return 0; } } int this[char c, params char[] args] { get { return 0; } } void M(C c) { int x; x = this[]; //CS0443 - can't omit all x = c[0]; x = c[0, 1]; x = c[0, 1, 2]; x = c[new int[3]]; x = c[args: new int[3]]; x = c['a']; x = c['a', 'b']; x = c['a', 'b', 'c']; x = c['a', new char[3]]; x = c['a', args: new char[3]]; x = c[args: new char[3], c: 'a']; } }"; CreateCompilation(source).VerifyDiagnostics( // (9,18): error CS0443: Syntax error; value expected Diagnostic(ErrorCode.ERR_ValueExpected, "]")); } [Fact] public void StaticIndexer() { var source = @"class C { // Illegal, but we shouldn't blow up public static int this[char c] { get { return 0; } } //CS0106 - illegal modifier public static void Main() { int x = C['a']; //CS0119 - can't use a type here int y = new C()['a']; //we don't even check for this kind of error because it's always cascading } }"; CreateCompilation(source).VerifyDiagnostics( // (4,23): error CS0106: The modifier 'static' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(4, 23), // (8,17): error CS0119: 'C' is a 'type', which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "C").WithArguments("C", "type").WithLocation(8, 17)); } [Fact] public void OverridingAndHidingWithExplicitIndexerName() { var source = @"using System; using System.Runtime.CompilerServices; public class A { public virtual int this[int x] { get { Console.WriteLine(""A""); return 0; } } } public class B : A { [IndexerName(""NotItem"")] public int this[int x] { get { Console.WriteLine(""B""); return 0; } } } public class C : B { public override int this[int x] { get { Console.WriteLine(""C""); return 0; } } }"; // Doesn't matter that B's indexer has an explicit name - the symbols are all called "this[]". CreateCompilation(source).VerifyDiagnostics( // (19,16): warning CS0114: 'B.this[int]' hides inherited member 'A.this[int]'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "this").WithArguments("B.this[int]", "A.this[int]"), // (31,25): error CS0506: 'C.this[int]': cannot override inherited member 'B.this[int]' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "this").WithArguments("C.this[int]", "B.this[int]")); } [ClrOnlyFact] public void CanBeReferencedByName() { var source = @" interface I { event System.Action E; int P { get; set; } int this[int x] { set; } } class C : I { event System.Action I.E { add { } remove { } } public event System.Action E; int I.P { get; set; } public int P { get; set; } int I.this[int x] { set { } } public int this[int x] { set { } } } "; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var globalNamespace = module.GlobalNamespace; var compilation = module.DeclaringCompilation; Assert.Equal(isFromSource, compilation != null); //// Source interface var @interface = globalNamespace.GetMember<NamedTypeSymbol>("I"); if (isFromSource) { Assert.True(@interface.IsFromCompilation(compilation)); } var interfaceEvent = @interface.GetMember<EventSymbol>("E"); var interfaceProperty = @interface.GetMember<PropertySymbol>("P"); var interfaceIndexer = @interface.Indexers.Single(); Assert.True(interfaceEvent.CanBeReferencedByName); Assert.True(interfaceProperty.CanBeReferencedByName); Assert.False(interfaceIndexer.CanBeReferencedByName); //// Source class var @class = globalNamespace.GetMember<NamedTypeSymbol>("C"); if (isFromSource) { Assert.True(@class.IsFromCompilation(compilation)); } var classEventImpl = @class.GetMembers().Where(m => m.GetExplicitInterfaceImplementations().Contains(interfaceEvent)).Single(); var classPropertyImpl = @class.GetMembers().Where(m => m.GetExplicitInterfaceImplementations().Contains(interfaceProperty)).Single(); var classIndexerImpl = @class.GetMembers().Where(m => m.GetExplicitInterfaceImplementations().Contains(interfaceIndexer)).Single(); Assert.False(classEventImpl.CanBeReferencedByName); Assert.False(classPropertyImpl.CanBeReferencedByName); Assert.False(classIndexerImpl.CanBeReferencedByName); var classEvent = @class.GetMember<EventSymbol>("E"); var classProperty = @class.GetMember<PropertySymbol>("P"); var classIndexer = @class.Indexers.Single(); Assert.True(classEvent.CanBeReferencedByName); Assert.True(classProperty.CanBeReferencedByName); Assert.False(classIndexer.CanBeReferencedByName); }; CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] public void RegressFinalValidationAssert() { var source = @"class C { int this[int x] { get { return x; } } void M() { System.Console.WriteLine(this[0]); } }"; CreateCompilation(source).VerifyDiagnostics(); } /// <summary> /// The Name and IsIndexer bits of explicitly implemented interface indexers do not roundtrip. /// This is unfortunate, but less so that having something declared with an IndexerDeclarationSyntax /// return false for IsIndexer. /// </summary> [ClrOnlyFact] public void ExplicitInterfaceImplementationIndexers() { var text = @" public interface I { int this[int x] { set; } } public class C : I { int I.this[int x] { set { } } } "; Action<ModuleSymbol> sourceValidator = module => { var globalNamespace = module.GlobalNamespace; var classC = globalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.Equal(0, classC.Indexers.Length); //excludes explicit implementations var classCIndexer = classC.GetMembers().Where(s => s.Kind == SymbolKind.Property).Single(); Assert.Equal("I.this[]", classCIndexer.Name); //interface name + WellKnownMemberNames.Indexer Assert.True(classCIndexer.IsIndexer()); //since declared with IndexerDeclarationSyntax }; Action<ModuleSymbol> metadataValidator = module => { var globalNamespace = module.GlobalNamespace; var classC = globalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.Equal(0, classC.Indexers.Length); //excludes explicit implementations var classCIndexer = classC.GetMembers().Where(s => s.Kind == SymbolKind.Property).Single(); Assert.Equal("I.Item", classCIndexer.Name); //name does not reflect WellKnownMemberNames.Indexer Assert.False(classCIndexer.IsIndexer()); //not the default member of C }; CompileAndVerify(text, sourceSymbolValidator: sourceValidator, symbolValidator: metadataValidator); } [Fact] public void NoAutoIndexers() { var source = @"class B { public virtual int this[int x] { get; set; } }"; CreateCompilation(source).VerifyDiagnostics( // (3,38): error CS0501: 'B.this[int].get' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("B.this[int].get"), // (3,43): error CS0501: 'B.this[int].set' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("B.this[int].set")); } [Fact] public void BaseIndexerAccess() { var source = @"public class Base { public int this[int x] { get { return x; } } } public class Derived : Base { public new int this[int x] { get { return x; } } void Method() { int x = base[1]; } }"; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var indexerAccessSyntax = GetElementAccessExpressions(tree.GetCompilationUnitRoot()).Single(); var baseClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseIndexer = baseClass.Indexers.Single(); // Confirm that the base indexer is used (even though the derived indexer signature matches). var model = comp.GetSemanticModel(tree); var symbolInfo = model.GetSymbolInfo(indexerAccessSyntax); Assert.Equal(baseIndexer.GetPublicSymbol(), symbolInfo.Symbol); } /// <summary> /// Indexers cannot have ref params in source, but they can in metadata. /// </summary> [Fact] public void IndexerWithRefParameter_Access() { var source = @" class Test { static void Main() { RefIndexer r = new RefIndexer(); int x = 1; x = r[ref x]; r[ref x] = 1; r[ref x]++; r[ref x] += 2; } } "; var compilation = CreateCompilation(source, new[] { TestReferences.SymbolsTests.Indexers }); compilation.VerifyDiagnostics( // (8,13): error CS1545: Property, indexer, or event 'RefIndexer.this[ref int]' is not supported by the language; try directly calling accessor methods 'RefIndexer.get_Item(ref int)' or 'RefIndexer.set_Item(ref int, int)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "r[ref x]").WithArguments("RefIndexer.this[ref int]", "RefIndexer.get_Item(ref int)", "RefIndexer.set_Item(ref int, int)"), // (9,9): error CS1545: Property, indexer, or event 'RefIndexer.this[ref int]' is not supported by the language; try directly calling accessor methods 'RefIndexer.get_Item(ref int)' or 'RefIndexer.set_Item(ref int, int)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "r[ref x]").WithArguments("RefIndexer.this[ref int]", "RefIndexer.get_Item(ref int)", "RefIndexer.set_Item(ref int, int)"), // (10,9): error CS1545: Property, indexer, or event 'RefIndexer.this[ref int]' is not supported by the language; try directly calling accessor methods 'RefIndexer.get_Item(ref int)' or 'RefIndexer.set_Item(ref int, int)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "r[ref x]").WithArguments("RefIndexer.this[ref int]", "RefIndexer.get_Item(ref int)", "RefIndexer.set_Item(ref int, int)"), // (11,9): error CS1545: Property, indexer, or event 'RefIndexer.this[ref int]' is not supported by the language; try directly calling accessor methods 'RefIndexer.get_Item(ref int)' or 'RefIndexer.set_Item(ref int, int)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "r[ref x]").WithArguments("RefIndexer.this[ref int]", "RefIndexer.get_Item(ref int)", "RefIndexer.set_Item(ref int, int)")); } /// <summary> /// Indexers cannot have ref params in source, but they can in metadata. /// </summary> [Fact] public void IndexerWithRefParameter_CallAccessor() { var source = @" class Test { static void Main() { RefIndexer r = new RefIndexer(); int x = 1; x = r.get_Item(ref x); r.set_Item(ref x, 1); } } "; var compilation = CreateCompilation(source, new[] { TestReferences.SymbolsTests.Indexers }); compilation.VerifyDiagnostics(); } /// <summary> /// Indexers cannot have ref params in source, but they can in metadata. /// </summary> [Fact] public void IndexerWithRefParameter_Override() { var source = @" class Test : RefIndexer { public override int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilation(source, new MetadataReference[] { TestReferences.SymbolsTests.Indexers }); compilation.VerifyDiagnostics( // (4,25): error CS0115: 'Test.this[int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Test.this[int]")); } /// <summary> /// Indexers cannot have ref params in source, but they can in metadata. /// </summary> [Fact] public void IndexerWithRefParameter_ImplicitlyImplement() { var source = @" class Test : IRefIndexer { public int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilation(source, new[] { TestReferences.SymbolsTests.Indexers }); // Normally, we wouldn't see errors for the accessors, but here we do because the indexer is bogus. compilation.VerifyDiagnostics( // (2,7): error CS0535: 'Test' does not implement interface member 'IRefIndexer.get_Item(ref int)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IRefIndexer").WithArguments("Test", "IRefIndexer.get_Item(ref int)"), // (2,7): error CS0535: 'Test' does not implement interface member 'IRefIndexer.set_Item(ref int, int)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IRefIndexer").WithArguments("Test", "IRefIndexer.set_Item(ref int, int)")); } /// <summary> /// Indexers cannot have ref params in source, but they can in metadata. /// </summary> [Fact] public void IndexerWithRefParameter_ExplicitlyImplement() { var source = @" class Test : IRefIndexer { int IRefIndexer.this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilation(source, new MetadataReference[] { TestReferences.SymbolsTests.Indexers }); // Normally, we wouldn't see errors for the accessors, but here we do because the indexer is bogus. compilation.VerifyDiagnostics( // (4,21): error CS0539: 'Test.this[int]' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test.this[int]"), // (2,7): error CS0535: 'Test' does not implement interface member 'IRefIndexer.get_Item(ref int)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IRefIndexer").WithArguments("Test", "IRefIndexer.get_Item(ref int)"), // (2,7): error CS0535: 'Test' does not implement interface member 'IRefIndexer.set_Item(ref int, int)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IRefIndexer").WithArguments("Test", "IRefIndexer.set_Item(ref int, int)")); } [Fact] public void IndexerNameAttribute() { var source = @" using System.Runtime.CompilerServices; class B { [IndexerName(""A"")] public virtual int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").Indexers.Single(); Assert.Equal(WellKnownMemberNames.Indexer, indexer.Name); Assert.Equal("A", indexer.MetadataName); Assert.Equal("get_A", indexer.GetMethod.Name); Assert.Equal("get_A", indexer.GetMethod.MetadataName); Assert.Equal("set_A", indexer.SetMethod.Name); Assert.Equal("set_A", indexer.SetMethod.MetadataName); } [WorkItem(528830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528830")] [Fact(Skip = "528830")] public void EscapedIdentifierInIndexerNameAttribute() { var source = @" using System.Runtime.CompilerServices; interface I { [IndexerName(""@indexer"")] int this[int x] { get; set; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I").Indexers.Single(); Assert.Equal("@indexer", indexer.MetadataName); Assert.Equal("get_@indexer", indexer.GetMethod.MetadataName); Assert.Equal("set_@indexer", indexer.SetMethod.MetadataName); } [Fact] public void NameNotCopiedOnOverride1() { var source = @" using System.Runtime.CompilerServices; class B { [IndexerName(""A"")] public virtual int this[int x] { get { return 0; } set { } } } class D : B { public override int this[int x] { get { return 0; } set { } } [IndexerName(""A"")] //error since name isn't copied down to override public int this[int x, int y] { get { return 0; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (15,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } [Fact] public void NameNotCopiedOnOverride2() { var source = @" using System.Runtime.CompilerServices; class B { [IndexerName(""A"")] public virtual int this[int x] { get { return 0; } set { } } } class D : B { [IndexerName(""A"")] //dev10 didn't allow this, but it should eliminate the error public override int this[int x] { get { return 0; } set { } } [IndexerName(""A"")] //error since name isn't copied down to override public int this[int x, int y] { get { return 0; } set { } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var derivedType = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("D"); Assert.True(derivedType.Indexers.All(i => i.MetadataName == "A")); } [Fact] public void NameNotCopiedOnOverride3() { var source = @" using System.Runtime.CompilerServices; class B { [IndexerName(""A"")] public virtual int this[int x] { get { return 0; } set { } } } class D : B { public override int this[int x] { get { return 0; } set { } } // If the name of the overridden indexer was copied, this would be an error. public int this[int x, int y] { get { return 0; } set { } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void IndexerNameLookup1() { var source = @" using System.Runtime.CompilerServices; class A { public const string get_X = ""X""; } class B : A { [IndexerName(C.get_X)] public int this[int x] { get { return 0; } } } class C : B { [IndexerName(get_X)] public int this[int x, int y] { get { return 0; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var classA = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var classB = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B"); var classC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var get_XA = classA.GetMember<FieldSymbol>("get_X"); var get_XB = classB.GetMember<MethodSymbol>("get_X"); var get_XC = classC.GetMember<MethodSymbol>("get_X"); Assert.Equal("X", get_XB.AssociatedSymbol.MetadataName); Assert.Equal("X", get_XC.AssociatedSymbol.MetadataName); } [Fact] public void IndexerNameLookup2() { var source = @" using System.Runtime.CompilerServices; class A { public const string get_X = ""X""; [IndexerName(get_X)] public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,30): error CS0102: The type 'A' already contains a definition for 'get_X' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("A", "get_X")); var classA = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); Assert.Equal("X", classA.Indexers.Single().MetadataName); } [Fact] public void IndexerNameLookup3() { var source = @" using System.Runtime.CompilerServices; public class MyAttribute : System.Attribute { public MyAttribute(object o) { } } class A { [IndexerName(get_Item)] public int this[int x] { get { return 0; } } // Doesn't matter what attribute it is or what member it's on - can't see indexer members. [MyAttribute(get_Item)] int x; } "; // NOTE: Dev10 reports CS0571 for MyAttribute's use of get_Item var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,18): error CS0571: 'A.this[int].get': cannot explicitly call operator or accessor // [IndexerName(get_Item)] Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("A.this[int].get"), // (15,18): error CS0571: 'A.this[int].get': cannot explicitly call operator or accessor // [MyAttribute(get_Item)] Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("A.this[int].get"), // (16,9): warning CS0169: The field 'A.x' is never used // int x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("A.x")); } [Fact] public void IndexerNameLookup4() { var source = @" using System.Runtime.CompilerServices; class A { [IndexerName(B.get_Item)] public int this[int x] { get { return 0; } } } class B { [IndexerName(A.get_Item)] public int this[int x] { get { return 0; } } } "; // NOTE: Dev10 reports CS0117 in A, but CS0571 in B var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,20): error CS0571: 'B.this[int].get': cannot explicitly call operator or accessor // [IndexerName(B.get_Item)] Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("B.this[int].get"), // (12,20): error CS0571: 'A.this[int].get': cannot explicitly call operator or accessor // [IndexerName(A.get_Item)] Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("A.this[int].get")); } [Fact] public void IndexerNameLookup5() { var source = @" using System.Runtime.CompilerServices; class A { public const string get_Item = ""X""; } class B : A { public const string C = get_Item; [IndexerName(C)] public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [Fact] public void IndexerNameLookupClass() { var source = @" using System.Runtime.CompilerServices; class A { public const string Constant1 = B.Constant1; public const string Constant2 = B.Constant2; } class B { public const string Constant1 = ""X""; public const string Constant2 = A.Constant2; [IndexerName(A.Constant1)] public int this[int x] { get { return 0; } } [IndexerName(A.Constant2)] public int this[long x] { get { return 0; } } } "; // CONSIDER: this cascading is a bit verbose. CreateCompilation(source).VerifyDiagnostics( // (18,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(A.Constant2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "A.Constant2"), // (7,25): error CS0110: The evaluation of the constant value for 'A.Constant2' involves a circular definition // public const string Constant2 = B.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("A.Constant2"), // (19,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type // public int this[long x] { get { return 0; } } Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } [Fact] public void IndexerNameLookupStruct() { var source = @" using System.Runtime.CompilerServices; struct A { public const string Constant1 = B.Constant1; public const string Constant2 = B.Constant2; } struct B { public const string Constant1 = ""X""; public const string Constant2 = A.Constant2; [IndexerName(A.Constant1)] public int this[int x] { get { return 0; } } [IndexerName(A.Constant2)] public int this[long x] { get { return 0; } } } "; // CONSIDER: this cascading is a bit verbose. CreateCompilation(source).VerifyDiagnostics( // (18,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(A.Constant2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "A.Constant2"), // (13,25): error CS0110: The evaluation of the constant value for 'A.Constant2' involves a circular definition // public const string Constant2 = A.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("A.Constant2"), // (19,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type // public int this[long x] { get { return 0; } } Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } [Fact] public void IndexerNameLookupInterface() { var source = @" using System.Runtime.CompilerServices; interface A { const string Constant1 = B.Constant1; const string Constant2 = B.Constant2; } interface B { const string Constant1 = ""X""; const string Constant2 = A.Constant2; [IndexerName(A.Constant1)] int this[int x] { get; } [IndexerName(A.Constant2)] int this[long x] { get; } } "; // CONSIDER: this cascading is a bit verbose. CreateCompilation(source, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (18,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(A.Constant2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "A.Constant2").WithLocation(18, 18), // (7,18): error CS0110: The evaluation of the constant value for 'A.Constant2' involves a circular definition // const string Constant2 = B.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("A.Constant2").WithLocation(7, 18), // (19,9): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type // int this[long x] { get; } Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this").WithLocation(19, 9), // (12,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant1 = "X"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant1").WithArguments("default interface implementation", "8.0").WithLocation(12, 18), // (13,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant2 = A.Constant2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant2").WithArguments("default interface implementation", "8.0").WithLocation(13, 18), // (6,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant1 = B.Constant1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant1").WithArguments("default interface implementation", "8.0").WithLocation(6, 18), // (7,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant2 = B.Constant2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant2").WithArguments("default interface implementation", "8.0").WithLocation(7, 18) ); } [Fact] public void IndexerNameLookupGenericClass() { var source = @" using System.Runtime.CompilerServices; class A<T> { public const string Constant1 = B<string>.Constant1; public const string Constant2 = B<int>.Constant2; [IndexerName(B<byte>.Constant2)] public int this[long x] { get { return 0; } } } class B<T> { public const string Constant1 = ""X""; public const string Constant2 = A<bool>.Constant2; [IndexerName(A<char>.Constant1)] public int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (9,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(B<byte>.Constant2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "B<byte>.Constant2"), // (7,25): error CS0110: The evaluation of the constant value for 'A<T>.Constant2' involves a circular definition // public const string Constant2 = B<int>.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("A<T>.Constant2")); } [Fact] public void IndexerNameLookupGenericStruct() { var source = @" using System.Runtime.CompilerServices; struct A<T> { public const string Constant1 = B<string>.Constant1; public const string Constant2 = B<int>.Constant2; [IndexerName(B<byte>.Constant2)] public int this[long x] { get { return 0; } } } struct B<T> { public const string Constant1 = ""X""; public const string Constant2 = A<bool>.Constant2; [IndexerName(A<char>.Constant1)] public int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (9,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(B<byte>.Constant2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "B<byte>.Constant2"), // (7,25): error CS0110: The evaluation of the constant value for 'A<T>.Constant2' involves a circular definition // public const string Constant2 = B<int>.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("A<T>.Constant2")); } [Fact] public void IndexerNameLookupGenericInterface() { var source = @" using System.Runtime.CompilerServices; interface A<T> { const string Constant1 = B<string>.Constant1; const string Constant2 = B<int>.Constant2; [IndexerName(B<byte>.Constant2)] int this[long x] { get; } } interface B<T> { const string Constant1 = ""X""; const string Constant2 = A<bool>.Constant2; [IndexerName(A<char>.Constant1)] int this[int x] { get; } } "; CreateCompilation(source, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (9,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(B<byte>.Constant2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "B<byte>.Constant2").WithLocation(9, 18), // (7,18): error CS0110: The evaluation of the constant value for 'A<T>.Constant2' involves a circular definition // const string Constant2 = B<int>.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("A<T>.Constant2").WithLocation(7, 18), // (15,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant1 = "X"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant1").WithArguments("default interface implementation", "8.0").WithLocation(15, 18), // (16,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant2 = A<bool>.Constant2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant2").WithArguments("default interface implementation", "8.0").WithLocation(16, 18), // (6,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant1 = B<string>.Constant1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant1").WithArguments("default interface implementation", "8.0").WithLocation(6, 18), // (7,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant2 = B<int>.Constant2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant2").WithArguments("default interface implementation", "8.0").WithLocation(7, 18) ); } [Fact] public void IndexerNameLookupTypeParameter() { var source = @" using System.Runtime.CompilerServices; class P { public const string Constant1 = Q.Constant1; public const string Constant2 = Q.Constant2; } class Q { public const string Constant1 = ""X""; public const string Constant2 = P.Constant2; } class A<T> where T : P { [IndexerName(T.Constant1)] public int this[long x] { get { return 0; } } } class B<T> where T : Q { [IndexerName(T.Constant2)] public int this[long x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (7,25): error CS0110: The evaluation of the constant value for 'P.Constant2' involves a circular definition // public const string Constant2 = Q.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("P.Constant2"), // (18,18): error CS0119: 'T' is a type parameter, which is not valid in the given context // [IndexerName(T.Constant1)] Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter"), // (24,18): error CS0119: 'T' is a type parameter, which is not valid in the given context // [IndexerName(T.Constant2)] Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter")); } [Fact] public void IndexerNameLookupEnum() { var source = @" using System.Runtime.CompilerServices; enum E { A, B, C = 6, D, E = F, F = E } class A { [IndexerName(E.A)] public int this[long x] { get { return 0; } } [IndexerName(E.B)] public int this[char x] { get { return 0; } } [IndexerName(E.C)] public int this[bool x] { get { return 0; } } [IndexerName(E.D)] public int this[uint x] { get { return 0; } } [IndexerName(E.E)] public int this[byte x] { get { return 0; } } [IndexerName(E.F)] public int this[ulong x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,5): error CS0110: The evaluation of the constant value for 'E.E' involves a circular definition // E = F, Diagnostic(ErrorCode.ERR_CircConstValue, "E").WithArguments("E.E"), // (16,18): error CS1503: Argument 1: cannot convert from 'E' to 'string' // [IndexerName(E.A)] Diagnostic(ErrorCode.ERR_BadArgType, "E.A").WithArguments("1", "E", "string"), // (19,18): error CS1503: Argument 1: cannot convert from 'E' to 'string' // [IndexerName(E.B)] Diagnostic(ErrorCode.ERR_BadArgType, "E.B").WithArguments("1", "E", "string"), // (22,18): error CS1503: Argument 1: cannot convert from 'E' to 'string' // [IndexerName(E.C)] Diagnostic(ErrorCode.ERR_BadArgType, "E.C").WithArguments("1", "E", "string"), // (25,18): error CS1503: Argument 1: cannot convert from 'E' to 'string' // [IndexerName(E.D)] Diagnostic(ErrorCode.ERR_BadArgType, "E.D").WithArguments("1", "E", "string"), // (28,18): error CS1503: Argument 1: cannot convert from 'E' to 'string' // [IndexerName(E.E)] Diagnostic(ErrorCode.ERR_BadArgType, "E.E").WithArguments("1", "E", "string"), // (31,18): error CS1503: Argument 1: cannot convert from 'E' to 'string' // [IndexerName(E.F)] Diagnostic(ErrorCode.ERR_BadArgType, "E.F").WithArguments("1", "E", "string")); } [Fact] public void IndexerNameLookupProperties() { var source = @" using System.Runtime.CompilerServices; class A { internal static string Name { get { return ""A""; } } [IndexerName(B.Name)] public int this[int x] { get { return 0; } } } class B { internal static string Name { get { return ""B""; } } [IndexerName(A.Name)] public int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (13,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(A.Name)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "A.Name"), // (7,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(B.Name)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "B.Name")); } [Fact] public void IndexerNameLookupCalls() { var source = @" using System.Runtime.CompilerServices; class A { internal static string GetName() { return ""A""; } [IndexerName(B.GetName())] public int this[int x] { get { return 0; } } } class B { internal static string GetName() { return ""B""; } [IndexerName(A.GetName())] public int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (7,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(B.GetName())] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "B.GetName()"), // (13,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(A.GetName())] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "A.GetName()")); } [Fact] public void IndexerNameLookupNonExistent() { var source = @" using System.Runtime.CompilerServices; class A { [IndexerName(B.Fake)] public int this[int x] { get { return 0; } } } class B { [IndexerName(A.Fake)] public int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (11,20): error CS0117: 'A' does not contain a definition for 'Fake' // [IndexerName(A.Fake)] Diagnostic(ErrorCode.ERR_NoSuchMember, "Fake").WithArguments("A", "Fake"), // (6,20): error CS0117: 'B' does not contain a definition for 'Fake' // [IndexerName(B.Fake)] Diagnostic(ErrorCode.ERR_NoSuchMember, "Fake").WithArguments("B", "Fake")); } [Fact] public void IndexerNameNotEmitted() { var source = @" using System.Runtime.CompilerServices; class Program { [IndexerName(""A"")] public int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilation(source).VerifyDiagnostics(); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").Indexers.Single(); Assert.True(indexer.IsIndexer); Assert.Equal("A", indexer.MetadataName); Assert.True(indexer.GetAttributes().Single().IsTargetAttribute(indexer, AttributeDescription.IndexerNameAttribute)); CompileAndVerify(compilation, symbolValidator: module => { var peIndexer = (PEPropertySymbol)module.GlobalNamespace.GetTypeMember("Program").Indexers.Single(); Assert.True(peIndexer.IsIndexer); Assert.Equal("A", peIndexer.MetadataName); Assert.Empty(peIndexer.GetAttributes()); Assert.Empty(((PEModuleSymbol)module).GetCustomAttributesForToken(peIndexer.Handle)); }); } [WorkItem(545884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545884")] [Fact] public void IndexerNameDeadlock1() { var source = @" using System.Runtime.CompilerServices; class A { public const string Name = ""A""; [IndexerName(B.Name)] public int this[int x] { get { return 0; } } } class B { public const string Name = ""B""; [IndexerName(A.Name)] public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilation(source); var loopResult = Parallel.ForEach(compilation.GlobalNamespace.GetTypeMembers(), type => type.ForceComplete(null, default(CancellationToken))); Assert.True(loopResult.IsCompleted); compilation.VerifyDiagnostics(); } [WorkItem(545884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545884")] [Fact] public void IndexerNameDeadlock2() { var source = @" using System.Runtime.CompilerServices; class A { private const string Name = ""A""; [IndexerName(B.Name)] public int this[int x] { get { return 0; } } } class B { private const string Name = ""B""; [IndexerName(A.Name)] public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilation(source); var loopResult = Parallel.ForEach(compilation.GlobalNamespace.GetTypeMembers(), type => type.ForceComplete(null, default(CancellationToken))); Assert.True(loopResult.IsCompleted); compilation.VerifyDiagnostics( // (7,20): error CS0122: 'B.Name' is inaccessible due to its protection level // [IndexerName(B.Name)] Diagnostic(ErrorCode.ERR_BadAccess, "Name").WithArguments("B.Name"), // (14,20): error CS0122: 'A.Name' is inaccessible due to its protection level // [IndexerName(A.Name)] Diagnostic(ErrorCode.ERR_BadAccess, "Name").WithArguments("A.Name")); } [Fact] public void OverloadResolutionPrecedence() { var source = @"public class C { public int this[int x] { get { return 0; } } public int this[int x, int y = 1] { get { return 0; } } public int this[params int[] x] { get { return 0; } } void Method() { int x; x = this[1]; x = this[1, 2]; x = this[1, 2, 3]; x = this[new int[1]]; } }"; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); CheckOverloadResolutionResults(tree, model, "System.Int32 C.this[System.Int32 x] { get; }", "System.Int32 C.this[System.Int32 x, [System.Int32 y = 1]] { get; }", "System.Int32 C.this[params System.Int32[] x] { get; }", "System.Int32 C.this[params System.Int32[] x] { get; }"); } [Fact] public void OverloadResolutionOverriding() { var source = @"public class Base { public virtual int this[int x] { get { return 0; } } public virtual int this[int x, int y = 1] { get { return 0; } } public virtual int this[params int[] x] { get { return 0; } } } public class Derived : Base { public override int this[int x] { get { return 0; } } public override int this[int x, int y = 1] { get { return 0; } } public override int this[params int[] x] { get { return 0; } } void Method() { int x; x = this[1]; x = this[1, 2]; x = this[1, 2, 3]; x = base[1]; x = base[1, 2]; x = base[1, 2, 3]; } }"; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); CheckOverloadResolutionResults(tree, model, // NOTE: we'll actually emit calls to the corresponding base indexers "System.Int32 Derived.this[System.Int32 x] { get; }", "System.Int32 Derived.this[System.Int32 x, [System.Int32 y = 1]] { get; }", "System.Int32 Derived.this[params System.Int32[] x] { get; }", "System.Int32 Base.this[System.Int32 x] { get; }", "System.Int32 Base.this[System.Int32 x, [System.Int32 y = 1]] { get; }", "System.Int32 Base.this[params System.Int32[] x] { get; }"); } [Fact] public void OverloadResolutionFallbackInBase() { var source = @"public class Base { public int this[params int[] x] { get { return 0; } } } public class Derived : Base { public int this[int x] { get { return 0; } } public int this[int x, int y = 1] { get { return 0; } } void Method() { int x; x = this[1]; x = this[1, 2]; x = this[1, 2, 3]; x = base[1]; x = base[1, 2]; x = base[1, 2, 3]; } }"; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); CheckOverloadResolutionResults(tree, model, "System.Int32 Derived.this[System.Int32 x] { get; }", "System.Int32 Derived.this[System.Int32 x, [System.Int32 y = 1]] { get; }", "System.Int32 Base.this[params System.Int32[] x] { get; }", "System.Int32 Base.this[params System.Int32[] x] { get; }", "System.Int32 Base.this[params System.Int32[] x] { get; }", "System.Int32 Base.this[params System.Int32[] x] { get; }"); } [Fact] public void OverloadResolutionDerivedRemovesParamsModifier() { var source = @"abstract class Base { public abstract int this[Derived c1, Derived c2, params Derived[] c3] { get; } } class Derived : Base { public override int this[Derived C1, Derived C2, Derived[] C3] { get { return 0; } } //removes 'params' } class Test2 { public static void Main2() { Derived d = new Derived(); Base b = d; int x; x = b[d, d, d, d, d]; // Fine x = d[d, d, d, d, d]; // Fine } }"; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); CheckOverloadResolutionResults(tree, model, "System.Int32 Base.this[Derived c1, Derived c2, params Derived[] c3] { get; }", "System.Int32 Derived.this[Derived C1, Derived C2, params Derived[] C3] { get; }"); } [Fact] public void OverloadResolutionDerivedAddsParamsModifier() { var source = @"abstract class Base { public abstract int this[Derived c1, Derived c2, Derived[] c3] { get; } } class Derived : Base { public override int this[Derived C1, Derived C2, params Derived[] C3] { get { return 0; } } //adds 'params' } class Test2 { public static void Main2() { Derived d = new Derived(); Base b = d; int x; x = b[d, d, d, d, d]; // CS1501 x = d[d, d, d, d, d]; // CS1501 } }"; CreateCompilation(source).VerifyDiagnostics( // (16,13): error CS1501: No overload for method 'this' takes 5 arguments Diagnostic(ErrorCode.ERR_BadArgCount, "b[d, d, d, d, d]").WithArguments("this", "5"), // (17,13): error CS1501: No overload for method 'this' takes 5 arguments Diagnostic(ErrorCode.ERR_BadArgCount, "d[d, d, d, d, d]").WithArguments("this", "5")); } [WorkItem(542747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542747")] [Fact()] public void IndexerAccessorParameterIsSynthesized() { var text = @" struct Test { public byte this[byte p] { get { return p; } } } "; var comp = CreateCompilation(text); NamedTypeSymbol type01 = comp.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single(); var indexer = type01.GetMembers(WellKnownMemberNames.Indexer).Single() as PropertySymbol; Assert.NotNull(indexer.GetMethod); Assert.False(indexer.GetMethod.Parameters.IsEmpty); // VB is SynthesizedParameterSymbol; C# is SourceComplexParameterSymbol foreach (var p in indexer.GetMethod.Parameters) { Assert.True(p.IsImplicitlyDeclared, "Parameter of Indexer Accessor"); } } [WorkItem(542831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542831")] [Fact] public void ProtectedBaseIndexer() { var text = @" public class Base { protected int this[int index] { get { return 0; } } } public class Derived : Base { public int M() { return base[0]; } } "; CreateCompilation(text).VerifyDiagnostics(); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void SameSignaturesDifferentNames() { var ilSource = @" .class public auto ansi beforefieldinit SameSignaturesDifferentNames extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Accessor1')} .method public hidebysig specialname instance int32 Accessor1(int32 x, int64 y) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance void Accessor2(int32 x, int64 y, int32 'value') cil managed { ret } .method public hidebysig specialname instance void Accessor3(int32 x, int64 y, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Indexer1(int32, int64) { .get instance int32 SameSignaturesDifferentNames::Accessor1(int32, int64) .set instance void SameSignaturesDifferentNames::Accessor2(int32, int64, int32) } .property instance int32 Indexer2(int32, int64) { .get instance int32 SameSignaturesDifferentNames::Accessor1(int32, int64) .set instance void SameSignaturesDifferentNames::Accessor3(int32, int64, int32) } }"; var cSharpSource = @" class Test { static void Main() { SameSignaturesDifferentNames s = new SameSignaturesDifferentNames(); System.Console.WriteLine(s[0, 1]); } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (7,34): error CS0121: The call is ambiguous between the following methods or properties: 'SameSignaturesDifferentNames.this[int, long]' and 'SameSignaturesDifferentNames.this[int, long]' Diagnostic(ErrorCode.ERR_AmbigCall, "s[0, 1]").WithArguments("SameSignaturesDifferentNames.this[int, long]", "SameSignaturesDifferentNames.this[int, long]")); } [WorkItem(543261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543261")] [ClrOnlyFact] public void OverrideOneAccessorOnly() { var source = @"class A { public virtual object this[object index] { get { return null; } set { } } } class B1 : A { public override object this[object index] { get { return base[index]; } } } class B2 : A { public override object this[object index] { set { base[index] = value; } } } class C { static void M(B1 _1, B2 _2) { _1[null] = _1[null]; _2[null] = _2[null]; } }"; CompileAndVerify(source); } private static void CheckOverloadResolutionResults(SyntaxTree tree, SemanticModel model, params string[] expected) { var actual = GetElementAccessExpressions(tree.GetCompilationUnitRoot()).Select(syntax => model.GetSymbolInfo(syntax).Symbol.ToTestDisplayString()); AssertEx.Equal(expected, actual, itemInspector: s => string.Format("\"{0}\"", s)); } private static IEnumerable<ElementAccessExpressionSyntax> GetElementAccessExpressions(SyntaxNode node) { return node == null ? SpecializedCollections.EmptyEnumerable<ElementAccessExpressionSyntax>() : node.DescendantNodesAndSelf().Where(s => s.IsKind(SyntaxKind.ElementAccessExpression)).Cast<ElementAccessExpressionSyntax>(); } [Fact] public void PartialType() { var text1 = @" partial class C { public int this[int x] { get { return 0; } set { } } }"; var text2 = @" partial class C { public void M() {} } "; var compilation = CreateCompilation(new string[] { text1, text2 }); Assert.True(((TypeSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single()).GetMembers().Any(x => x.IsIndexer())); //test with text inputs reversed in case syntax ordering predicate ever changes. compilation = CreateCompilation(new string[] { text2, text1 }); Assert.True(((TypeSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single()).GetMembers().Any(x => x.IsIndexer())); } [WorkItem(543957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543957")] [Fact] public void SemanticModelIndexerGroupHiding() { var source = @"public class Base { public int this[int x] { get { return x; } } public virtual int this[int x, int y] { get { return x; } } public int this[int x, int y, int z] { get { return x; } } } public class Derived : Base { public new int this[int x] { get { return x; } } public override int this[int x, int y] { get { return x; } } void Method() { int x; x = this[1]; x = base[1]; Derived d = new Derived(); x = d[1]; Base b = new Base(); x = b[1]; Wrapper w = new Wrapper(); x = w.Base[1]; x = w.Derived[1]; x = (d ?? w.Derived)[1]; } } public class Wrapper { public Base Base; public Derived Derived; } "; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); var elementAccessSyntaxes = GetElementAccessExpressions(tree.GetCompilationUnitRoot()); // The access itself doesn't have an indexer group. foreach (var syntax in elementAccessSyntaxes) { Assert.Equal(0, model.GetIndexerGroup(syntax).Length); } var baseType = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var derivedType = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var baseIndexers = baseType.Indexers; var derivedIndexers = derivedType.Indexers; var baseIndexer3 = baseIndexers.Single(indexer => indexer.ParameterCount == 3); var baseIndexerGroup = baseIndexers; var derivedIndexerGroup = derivedIndexers.Concat(ImmutableArray.Create<PropertySymbol>(baseIndexer3)); var receiverSyntaxes = elementAccessSyntaxes.Select(access => access.Expression); Assert.Equal(7, receiverSyntaxes.Count()); // The receiver of each access expression has an indexer group. foreach (var syntax in receiverSyntaxes) { var type = model.GetTypeInfo(syntax).Type.GetSymbol(); Assert.NotNull(type); var indexerGroup = model.GetIndexerGroup(syntax); if (type.Equals(baseType)) { Assert.True(indexerGroup.SetEquals(baseIndexerGroup.GetPublicSymbols(), EqualityComparer<IPropertySymbol>.Default)); } else if (type.Equals(derivedType)) { Assert.True(indexerGroup.SetEquals(derivedIndexerGroup.GetPublicSymbols(), EqualityComparer<IPropertySymbol>.Default)); } else { Assert.True(false, "Unexpected type " + type.ToTestDisplayString()); } } } [WorkItem(543957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543957")] [Fact] public void SemanticModelIndexerGroupAccessibility() { var source = @"class Base { private int this[int x] { get { return 0; } } protected int this[string x] { get { return 0; } } public int this[bool x] { get { return 0; } } void M() { int x; x = this[1]; //all } } class Derived1 : Base { void M() { int x; x = this[""string""]; //public and protected Derived2 d = new Derived2(); x = d[true]; //only public } } class Derived2 : Base { } "; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); var elementAccessSyntaxes = GetElementAccessExpressions(tree.GetCompilationUnitRoot()); // The access itself doesn't have an indexer group. foreach (var syntax in elementAccessSyntaxes) { Assert.Equal(0, model.GetIndexerGroup(syntax).Length); } var baseType = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var derived1Type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived1"); var derived2Type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived2"); var indexers = baseType.Indexers; var publicIndexer = indexers.Single(indexer => indexer.DeclaredAccessibility == Accessibility.Public); var protectedIndexer = indexers.Single(indexer => indexer.DeclaredAccessibility == Accessibility.Protected); var privateIndexer = indexers.Single(indexer => indexer.DeclaredAccessibility == Accessibility.Private); var receiverSyntaxes = elementAccessSyntaxes.Select(access => access.Expression).ToArray(); Assert.Equal(3, receiverSyntaxes.Length); // In declaring type, can see everything. Assert.True(model.GetIndexerGroup(receiverSyntaxes[0]).SetEquals( ImmutableArray.Create<PropertySymbol>(publicIndexer, protectedIndexer, privateIndexer).GetPublicSymbols(), EqualityComparer<IPropertySymbol>.Default)); // In subtype of declaring type, can see non-private. Assert.True(model.GetIndexerGroup(receiverSyntaxes[1]).SetEquals( ImmutableArray.Create<PropertySymbol>(publicIndexer, protectedIndexer).GetPublicSymbols(), EqualityComparer<IPropertySymbol>.Default)); // In subtype of declaring type, can only see public (or internal) members of other subtypes. Assert.True(model.GetIndexerGroup(receiverSyntaxes[2]).SetEquals( ImmutableArray.Create<PropertySymbol>(publicIndexer).GetPublicSymbols(), EqualityComparer<IPropertySymbol>.Default)); } [WorkItem(545851, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545851")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void DistinctOptionalParameterValues() { var source1 = @".class abstract public A { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance int32 get_P(int32 x, [opt] int32 y) { .param[2] = int32(1) } .method public abstract virtual instance void set_P(int32 x, [opt] int32 y, int32 v) { .param[2] = int32(2) } .property instance int32 P(int32, int32) { .get instance int32 A::get_P(int32, int32) .set instance void A::set_P(int32, int32, int32) } }"; var reference1 = CompileIL(source1); var source2 = @"using System; class B : A { public override int this[int x, int y = 3] { get { Console.WriteLine(""get_P: {0}"", y); return 0; } set { Console.WriteLine(""set_P: {0}"", y); } } } class C { static void Main() { B b = new B(); b[0] = b[0]; b[1] += 1; A a = b; a[0] = a[0]; a[1] += 1; // Dev11 uses get_P default for both } }"; var compilation2 = CompileAndVerify(source2, references: new[] { reference1 }, expectedOutput: @"get_P: 3 set_P: 3 get_P: 3 set_P: 3 get_P: 1 set_P: 2 get_P: 1 set_P: 1"); } [Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")] public void RetargetingIndexerMetadataName() { #region "Source" var src1 = @"using System; public interface IGoo { int this[int i] { get; } } public class Goo : IGoo { public int this[int i] { get { return i; } } } "; var src2 = @"using System; class Test { public void M() { IGoo igoo = new Goo(); var local = igoo[100]; } } "; #endregion var comp1 = CreateEmptyCompilation(src1, new[] { TestMetadata.Net40.mscorlib }); var comp2 = CreateCompilation(src2, new[] { new CSharpCompilationReference(comp1) }); var typeSymbol = comp1.SourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("IGoo"); var idxSymbol = typeSymbol.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.NotNull(idxSymbol); Assert.Equal("this[]", idxSymbol.Name); Assert.Equal("Item", idxSymbol.MetadataName); var tree = comp2.SyntaxTrees[0]; var model = comp2.GetSemanticModel(tree); ExpressionSyntax expr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().FirstOrDefault(); var idxSymbol2 = model.GetSymbolInfo(expr); Assert.NotNull(idxSymbol2.Symbol); Assert.Equal(WellKnownMemberNames.Indexer, idxSymbol2.Symbol.Name); Assert.Equal("Item", idxSymbol2.Symbol.MetadataName); } [Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")] public void SubstitutedIndexerMetadataName() { var source = @" class C<T> { int this[int x] { get { return 0; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var unsubstitutedType = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var unsubstitutedIndexer = unsubstitutedType.GetMember<SourcePropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal(WellKnownMemberNames.Indexer, unsubstitutedIndexer.Name); Assert.Equal("Item", unsubstitutedIndexer.MetadataName); var substitutedType = unsubstitutedType.Construct(comp.GetSpecialType(SpecialType.System_Int32)); var substitutedIndexer = substitutedType.GetMember<SubstitutedPropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal(WellKnownMemberNames.Indexer, substitutedIndexer.Name); Assert.Equal("Item", substitutedIndexer.MetadataName); } [Fact, WorkItem(806258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/806258")] public void ConflictWithTypeParameter() { var source = @" class C<Item, get_Item> { int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (4,9): error CS0102: The type 'C<Item, get_Item>' already contains a definition for 'Item' // int this[int x] { get { return 0; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("C<Item, get_Item>", "Item"), // (4,23): error CS0102: The type 'C<Item, get_Item>' already contains a definition for 'get_Item' // int this[int x] { get { return 0; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("C<Item, get_Item>", "get_Item")); } [Fact, WorkItem(806258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/806258")] public void ConflictWithTypeParameter_IndexerNameAttribute() { var source = @" using System.Runtime.CompilerServices; class C<A, get_A> { [IndexerName(""A"")] int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0102: The type 'C<A, get_A>' already contains a definition for 'A' // int this[int x] { get { return 0; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("C<A, get_A>", "A"), // (7,23): error CS0102: The type 'C<A, get_A>' already contains a definition for 'get_A' // int this[int x] { get { return 0; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("C<A, get_A>", "get_A")); } [Fact] public void IndexerNameNoConstantValue() { var source = @"using System.Runtime.CompilerServices; class C { const string F; [IndexerName(F)] object this[object o] { get { return null; } } }"; CreateCompilation(source).VerifyDiagnostics( // (4,18): error CS0145: A const field requires a value to be provided // const string F; Diagnostic(ErrorCode.ERR_ConstValueRequired, "F").WithLocation(4, 18), // (5,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(F)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F").WithLocation(5, 18)); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class IndexerTests : CSharpTestBase { [ClrOnlyFact] public void Indexers() { var source = @"using System.Runtime.CompilerServices; class C { [IndexerName(""P"")] internal string this[string index] { get { return null; } set { } } } interface I { object this[int i, params object[] args] { set; } } struct S { internal object this[string x] { get { return null; } } }"; Action<ModuleSymbol> validator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); CheckIndexer(type.Indexers.Single(), true, true, SpecialType.System_String, SpecialType.System_String); type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I"); CheckIndexer(type.Indexers.Single(), false, true, SpecialType.System_Object, SpecialType.System_Int32, SpecialType.None); type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("S"); CheckIndexer(type.Indexers.Single(), true, false, SpecialType.System_Object, SpecialType.System_String); }; CompileAndVerify( source: source, sourceSymbolValidator: validator, symbolValidator: validator, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); } [ClrOnlyFact] public void InterfaceImplementations() { var source = @"using System.Runtime.CompilerServices; interface IA { object this[string index] { get; set; } } interface IB { object this[string index] { get; } } interface IC { [IndexerName(""P"")] object this[string index] { get; set; } } class A : IA, IB, IC { object IA.this[string index] { get { return null; } set { } } object IB.this[string index] { get { return null; } } object IC.this[string index] { get { return null; } set { } } } class B : IA, IB, IC { public object this[string index] { get { return null; } set { } } } class C : IB, IC { [IndexerName(""Q"")] public object this[string index] { get { return null; } set { } } }"; var compilation = CompileAndVerify(source); compilation.VerifyDiagnostics(); var globalNamespace = (NamespaceSymbol)((CSharpCompilation)compilation.Compilation).GlobalNamespace; var type = globalNamespace.GetMember<NamedTypeSymbol>("IA"); CheckIndexer(type.Indexers.Single(), true, true, SpecialType.System_Object, SpecialType.System_String); type = globalNamespace.GetMember<NamedTypeSymbol>("IB"); CheckIndexer(type.Indexers.Single(), true, false, SpecialType.System_Object, SpecialType.System_String); type = globalNamespace.GetMember<NamedTypeSymbol>("IC"); CheckIndexer(type.Indexers.Single(), true, true, SpecialType.System_Object, SpecialType.System_String); type = globalNamespace.GetMember<NamedTypeSymbol>("A"); var typeAProperties = type.GetMembers().Where(m => m.Kind == SymbolKind.Property).Cast<PropertySymbol>().ToArray(); Assert.Equal(3, typeAProperties.Length); CheckIndexer(typeAProperties[0], true, true, SpecialType.System_Object, SpecialType.System_String); CheckIndexer(typeAProperties[1], true, false, SpecialType.System_Object, SpecialType.System_String); CheckIndexer(typeAProperties[2], true, true, SpecialType.System_Object, SpecialType.System_String); var sourceType = globalNamespace.GetMember<SourceNamedTypeSymbol>("B"); CheckIndexer(sourceType.Indexers.Single(), true, true, SpecialType.System_Object, SpecialType.System_String); var bridgeMethods = sourceType.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods; Assert.Equal(2, bridgeMethods.Length); Assert.True(bridgeMethods.Select(GetPairForSynthesizedExplicitImplementation).SetEquals(new[] { new KeyValuePair<string, string>("System.Object IC.this[System.String index].get", "System.Object B.this[System.String index].get"), new KeyValuePair<string, string>("void IC.this[System.String index].set", "void B.this[System.String index].set"), })); sourceType = globalNamespace.GetMember<SourceNamedTypeSymbol>("C"); CheckIndexer(sourceType.Indexers.Single(), true, true, SpecialType.System_Object, SpecialType.System_String); bridgeMethods = sourceType.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods; Assert.Equal(3, bridgeMethods.Length); Assert.True(bridgeMethods.Select(GetPairForSynthesizedExplicitImplementation).SetEquals(new[] { new KeyValuePair<string, string>("System.Object IB.this[System.String index].get", "System.Object C.this[System.String index].get"), new KeyValuePair<string, string>("System.Object IC.this[System.String index].get", "System.Object C.this[System.String index].get"), new KeyValuePair<string, string>("void IC.this[System.String index].set", "void C.this[System.String index].set"), })); } private static KeyValuePair<string, string> GetPairForSynthesizedExplicitImplementation(SynthesizedExplicitImplementationForwardingMethod bridge) { return new KeyValuePair<string, string>(bridge.ExplicitInterfaceImplementations.Single().ToTestDisplayString(), bridge.ImplementingMethod.ToTestDisplayString()); } private static void CheckIndexer(PropertySymbol property, bool hasGet, bool hasSet, SpecialType expectedType, params SpecialType[] expectedParameterTypes) { Assert.NotNull(property); Assert.True(property.IsIndexer); Assert.Equal(property.Type.SpecialType, expectedType); CheckParameters(property.Parameters, expectedParameterTypes); var getter = property.GetMethod; if (hasGet) { Assert.NotNull(getter); Assert.Equal(getter.ReturnType.SpecialType, expectedType); CheckParameters(getter.Parameters, expectedParameterTypes); } else { Assert.Null(getter); } var setter = property.SetMethod; if (hasSet) { Assert.NotNull(setter); Assert.True(setter.ReturnsVoid); CheckParameters(setter.Parameters, expectedParameterTypes.Concat(new[] { expectedType }).ToArray()); } else { Assert.Null(setter); } Assert.Equal(property.GetMethod != null, hasGet); Assert.Equal(property.SetMethod != null, hasSet); } private static void CheckParameters(ImmutableArray<ParameterSymbol> parameters, SpecialType[] expectedTypes) { Assert.Equal(parameters.Length, expectedTypes.Length); for (int i = 0; i < expectedTypes.Length; i++) { var parameter = parameters[i]; Assert.Equal(parameter.Ordinal, i); Assert.Equal(parameter.Type.SpecialType, expectedTypes[i]); } } [Fact] public void OverloadResolution() { var source = @"class C { int this[int x, int y] { get { return 0; } } int F(C c) { return this[0] + c[0, c] + c[1, 2, 3]; } }"; CreateCompilation(source).VerifyDiagnostics( // (9,16): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'C.this[int, int]' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "this[0]").WithArguments("y", "C.this[int, int]").WithLocation(9, 16), // (10,18): error CS1503: Argument 2: cannot convert from 'C' to 'int' Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("2", "C", "int").WithLocation(10, 18), // (11,13): error CS1501: No overload for method 'this' takes 3 arguments Diagnostic(ErrorCode.ERR_BadArgCount, "c[1, 2, 3]").WithArguments("this", "3").WithLocation(11, 13)); } [Fact] public void OverridingHiddenIndexer() { var source = @" using System.Runtime.CompilerServices; public class A { public virtual int this[int x] { get { return 0; } } } public class B : A { // Even though the user has specified a name for this indexer that // doesn't match the name of the base class accessor, we expect // it to hide A's indexer in subclasses (i.e. C). [IndexerName(""NotItem"")] public int this[int x] { get { return 0; } } //NB: not virtual } public class C : B { public override int this[int x] { get { return 0; } } }"; var compilation = CreateCompilation(source); // NOTE: we could eliminate WRN_NewOrOverrideExpected by putting a "new" modifier on B.this[] compilation.VerifyDiagnostics( // (15,16): warning CS0114: 'B.this[int]' hides inherited member 'A.this[int]'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "this").WithArguments("B.this[int]", "A.this[int]"), // (20,25): error CS0506: 'C.this[int]': cannot override inherited member 'B.this[int]' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "this").WithArguments("C.this[int]", "B.this[int]")); var classC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var indexerC = classC.Indexers.Single(); Assert.Null(indexerC.OverriddenProperty); Assert.Null(indexerC.GetMethod.OverriddenMethod); } [Fact] public void ImplicitlyImplementingIndexersWithDifferentNames_DifferentInterfaces_Source() { var text = @" using System.Runtime.CompilerServices; interface I1 { [IndexerName(""A"")] int this[int x] { get; } } interface I2 { [IndexerName(""B"")] int this[int x] { get; } } class C : I1, I2 { public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics(); var interface1 = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I1"); var interface1Indexer = interface1.Indexers.Single(); var interface2 = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I2"); var interface2Indexer = interface2.Indexers.Single(); var @class = compilation.GlobalNamespace.GetMember<SourceNamedTypeSymbol>("C"); var classIndexer = @class.Indexers.Single(); // All of the indexers have the same Name Assert.Equal(WellKnownMemberNames.Indexer, classIndexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, interface1Indexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, interface2Indexer.Name); // All of the indexers have different MetadataNames Assert.NotEqual(interface1Indexer.MetadataName, interface2Indexer.MetadataName); Assert.NotEqual(interface1Indexer.MetadataName, classIndexer.MetadataName); Assert.NotEqual(interface2Indexer.MetadataName, classIndexer.MetadataName); // classIndexer implements both Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interface1Indexer)); Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interface2Indexer)); var synthesizedExplicitImplementations = @class.GetSynthesizedExplicitImplementations(default(CancellationToken)).ForwardingMethods; Assert.Equal(2, synthesizedExplicitImplementations.Length); Assert.Equal(classIndexer.GetMethod, synthesizedExplicitImplementations[0].ImplementingMethod); Assert.Equal(classIndexer.GetMethod, synthesizedExplicitImplementations[1].ImplementingMethod); var interface1Getter = interface1Indexer.GetMethod; var interface2Getter = interface2Indexer.GetMethod; var interface1GetterImpl = synthesizedExplicitImplementations[0].ExplicitInterfaceImplementations.Single(); var interface2GetterImpl = synthesizedExplicitImplementations[1].ExplicitInterfaceImplementations.Single(); Assert.True(interface1Getter == interface1GetterImpl ^ interface1Getter == interface2GetterImpl); Assert.True(interface2Getter == interface1GetterImpl ^ interface2Getter == interface2GetterImpl); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ImplicitlyImplementingIndexersWithDifferentNames_DifferentInterfaces_Metadata() { var il = @" .class interface public abstract auto ansi I1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('A')} .method public hidebysig newslot specialname abstract virtual instance int32 get_A(int32 x) cil managed { } // end of method I1::get_A .property instance int32 A(int32) { .get instance int32 I1::get_A(int32) } // end of property I1::A } // end of class I1 .class interface public abstract auto ansi I2 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('B')} .method public hidebysig newslot specialname abstract virtual instance int32 get_B(int32 x) cil managed { } // end of method I2::get_B .property instance int32 B(int32) { .get instance int32 I2::get_B(int32) } // end of property I2::B } // end of class I2 "; var csharp = @" class C : I1, I2 { public int this[int x] { get { return 0; } } } "; CompileWithCustomILSource(csharp, il, compilation => { var interface1 = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I1"); var interface1Indexer = interface1.Indexers.Single(); var interface2 = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I2"); var interface2Indexer = interface2.Indexers.Single(); var @class = compilation.GlobalNamespace.GetMember<SourceNamedTypeSymbol>("C"); var classIndexer = @class.Indexers.Single(); // All of the indexers have the same Name Assert.Equal(WellKnownMemberNames.Indexer, classIndexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, interface1Indexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, interface2Indexer.Name); // All of the indexers have different MetadataNames Assert.NotEqual(interface1Indexer.MetadataName, interface2Indexer.MetadataName); Assert.NotEqual(interface1Indexer.MetadataName, classIndexer.MetadataName); Assert.NotEqual(interface2Indexer.MetadataName, classIndexer.MetadataName); // classIndexer implements both Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interface1Indexer)); Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interface2Indexer)); var synthesizedExplicitImplementations = @class.GetSynthesizedExplicitImplementations(default(CancellationToken)).ForwardingMethods; Assert.Equal(2, synthesizedExplicitImplementations.Length); Assert.Equal(classIndexer.GetMethod, synthesizedExplicitImplementations[0].ImplementingMethod); Assert.Equal(classIndexer.GetMethod, synthesizedExplicitImplementations[1].ImplementingMethod); var interface1Getter = interface1Indexer.GetMethod; var interface2Getter = interface2Indexer.GetMethod; var interface1GetterImpl = synthesizedExplicitImplementations[0].ExplicitInterfaceImplementations.Single(); var interface2GetterImpl = synthesizedExplicitImplementations[1].ExplicitInterfaceImplementations.Single(); Assert.True(interface1Getter == interface1GetterImpl ^ interface1Getter == interface2GetterImpl); Assert.True(interface2Getter == interface1GetterImpl ^ interface2Getter == interface2GetterImpl); }); } /// <summary> /// Metadata type has two indexers with the same signature but different names. /// Both are implicitly implemented by a single source indexer. /// </summary> [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ImplicitlyImplementingIndexersWithDifferentNames_SameInterface() { var il = @" .class interface public abstract auto ansi I1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('getter')} .method public hidebysig newslot specialname abstract virtual instance int32 getter(int32 x) cil managed { } // end of method I1::getter .property instance int32 A(int32) { .get instance int32 I1::getter(int32) } // end of property I1::A .property instance int32 B(int32) { .get instance int32 I1::getter(int32) } // end of property I1::B } // end of class I1 "; var csharp = @" class C : I1 { public int this[int x] { get { return 0; } } } "; CompileWithCustomILSource(csharp, il, compilation => { var @interface = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I1"); var interfaceIndexers = @interface.Indexers; Assert.Equal(2, interfaceIndexers.Length); Assert.Equal(interfaceIndexers[0].ToTestDisplayString(), interfaceIndexers[1].ToTestDisplayString()); var @class = compilation.GlobalNamespace.GetMember<SourceNamedTypeSymbol>("C"); var classIndexer = @class.Indexers.Single(); // classIndexer implements both Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interfaceIndexers[0])); Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interfaceIndexers[1])); var synthesizedExplicitImplementation = @class.GetSynthesizedExplicitImplementations(default(CancellationToken)).ForwardingMethods.Single(); Assert.Equal(classIndexer.GetMethod, synthesizedExplicitImplementation.ImplementingMethod); Assert.Equal(interfaceIndexers[0].GetMethod, synthesizedExplicitImplementation.ExplicitInterfaceImplementations.Single()); Assert.Equal(interfaceIndexers[1].GetMethod, synthesizedExplicitImplementation.ExplicitInterfaceImplementations.Single()); }); } /// <summary> /// Metadata type has two indexers with the same signature but different names. /// Both are explicitly implemented by a single source indexer, resulting in an /// ambiguity error. /// </summary> [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void AmbiguousExplicitIndexerImplementation() { // NOTE: could be done in C# using IndexerNameAttribute var il = @" .class interface public abstract auto ansi I1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('get_Item')} .method public hidebysig newslot specialname abstract virtual instance int32 get_Item(int32 x) cil managed { } // end of method I1::get_Item .property instance int32 A(int32) { .get instance int32 I1::get_Item(int32) } // end of property I1::A .property instance int32 B(int32) { .get instance int32 I1::get_Item(int32) } // end of property I1::B } // end of class I1 "; var csharp1 = @" class C : I1 { int I1.this[int x] { get { return 0; } } } "; var compilation = CreateCompilationWithILAndMscorlib40(csharp1, il).VerifyDiagnostics( // (4,12): warning CS0473: Explicit interface implementation 'C.I1.this[int]' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "this").WithArguments("C.I1.this[int]"), // (2,7): error CS0535: 'C' does not implement interface member 'I1.this[int]' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C", "I1.this[int]")); var @interface = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I1"); var interfaceIndexers = @interface.Indexers; Assert.Equal(2, interfaceIndexers.Length); Assert.Equal(interfaceIndexers[0].ToTestDisplayString(), interfaceIndexers[1].ToTestDisplayString()); var @class = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var classIndexer = @class.GetProperty("I1.this[]"); // One is implemented, the other is not (unspecified which) var indexer0Impl = @class.FindImplementationForInterfaceMember(interfaceIndexers[0]); var indexer1Impl = @class.FindImplementationForInterfaceMember(interfaceIndexers[1]); Assert.True(indexer0Impl == classIndexer ^ indexer1Impl == classIndexer); Assert.True(indexer0Impl == null ^ indexer1Impl == null); var csharp2 = @" class C : I1 { public int this[int x] { get { return 0; } } } "; compilation = CreateCompilationWithILAndMscorlib40(csharp2, il).VerifyDiagnostics(); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void HidingIndexerWithDifferentName() { // NOTE: could be done in C# using IndexerNameAttribute var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('A')} .method public hidebysig specialname instance int32 get_A(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 A(int32) { .get instance int32 Base::get_A(int32) } // end of property Base::A } // end of class Base "; var csharp = @" class Derived : Base { public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilationWithILAndMscorlib40(csharp, il); compilation.VerifyDiagnostics( // (4,16): warning CS0108: 'Derived.this[int]' hides inherited member 'Base.this[int]'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "this").WithArguments("Derived.this[int]", "Base.this[int]")); var baseClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseIndexer = baseClass.Indexers.Single(); var derivedClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var derivedIndexer = derivedClass.Indexers.Single(); // The indexers have the same Name Assert.Equal(WellKnownMemberNames.Indexer, derivedIndexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, baseIndexer.Name); // The indexers have different MetadataNames Assert.NotEqual(baseIndexer.MetadataName, derivedIndexer.MetadataName); Assert.Equal(baseIndexer, derivedIndexer.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void OverridingIndexerWithDifferentName() { // NOTE: could be done in C# using IndexerNameAttribute var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('A')} .method public hidebysig newslot specialname virtual instance int32 get_A(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 A(int32) { .get instance int32 Base::get_A(int32) } // end of property Base::A } // end of class Base "; var csharp = @" class Derived : Base { public override int this[int x] { get { return 0; } } } "; CompileWithCustomILSource(csharp, il, compilation => { var baseClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseIndexer = baseClass.Indexers.Single(); var derivedClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var derivedIndexer = derivedClass.Indexers.Single(); // Rhe indexers have the same Name Assert.Equal(WellKnownMemberNames.Indexer, derivedIndexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, baseIndexer.Name); // The indexers have different MetadataNames Assert.NotEqual(baseIndexer.MetadataName, derivedIndexer.MetadataName); Assert.Equal(baseIndexer, derivedIndexer.OverriddenProperty); }); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void HidingMultipleIndexers() { // NOTE: could be done in C# using IndexerNameAttribute var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('getter')} .method public hidebysig specialname instance int32 getter(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 A(int32) { .get instance int32 Base::getter(int32) } // end of property Base::A .property instance int32 B(int32) { .get instance int32 Base::getter(int32) } // end of property Base::B } // end of class Base "; var csharp = @" class Derived : Base { public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilationWithILAndMscorlib40(csharp, il); // As in dev10, we report only the first hidden member. compilation.VerifyDiagnostics( // (4,16): warning CS0108: 'Derived.this[int]' hides inherited member 'Base.this[int]'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "this").WithArguments("Derived.this[int]", "Base.this[int]")); var baseClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseIndexers = baseClass.Indexers; var derivedClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var derivedIndexer = derivedClass.Indexers.Single(); // The indexers have the same Name Assert.Equal(WellKnownMemberNames.Indexer, derivedIndexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, baseIndexers[0].Name); Assert.Equal(WellKnownMemberNames.Indexer, baseIndexers[1].Name); // The indexers have different MetadataNames Assert.NotEqual(baseIndexers[0].MetadataName, baseIndexers[1].MetadataName); Assert.NotEqual(baseIndexers[0].MetadataName, derivedIndexer.MetadataName); Assert.NotEqual(baseIndexers[1].MetadataName, derivedIndexer.MetadataName); // classIndexer implements both var hiddenMembers = derivedIndexer.OverriddenOrHiddenMembers.HiddenMembers; Assert.Equal(2, hiddenMembers.Length); Assert.Contains(baseIndexers[0], hiddenMembers); Assert.Contains(baseIndexers[1], hiddenMembers); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void OverridingMultipleIndexers() { // NOTE: could be done in C# using IndexerNameAttribute var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('getter')} .method public hidebysig newslot specialname virtual instance int32 getter(int32 x) cil managed { ldc.i4.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 A(int32) { .get instance int32 Base::getter(int32) } // end of property Base::A .property instance int32 B(int32) { .get instance int32 Base::getter(int32) } // end of property Base::B } // end of class Base "; var csharp = @" class Derived : Base { public override int this[int x] { get { return 0; } } } "; var compilation = CreateCompilationWithILAndMscorlib40(csharp, il).VerifyDiagnostics( // (4,25): error CS0462: The inherited members 'Base.this[int]' and 'Base.this[int]' have the same signature in type 'Derived', so they cannot be overridden Diagnostic(ErrorCode.ERR_AmbigOverride, "this").WithArguments("Base.this[int]", "Base.this[int]", "Derived")); var baseClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseIndexers = baseClass.Indexers; var derivedClass = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var derivedIndexer = derivedClass.Indexers.Single(); // The indexers have the same Name Assert.Equal(WellKnownMemberNames.Indexer, derivedIndexer.Name); Assert.Equal(WellKnownMemberNames.Indexer, baseIndexers[0].Name); Assert.Equal(WellKnownMemberNames.Indexer, baseIndexers[1].Name); // The indexers have different MetadataNames Assert.NotEqual(baseIndexers[0].MetadataName, baseIndexers[1].MetadataName); Assert.NotEqual(baseIndexers[0].MetadataName, derivedIndexer.MetadataName); Assert.NotEqual(baseIndexers[1].MetadataName, derivedIndexer.MetadataName); // classIndexer implements both var overriddenMembers = derivedIndexer.OverriddenOrHiddenMembers.OverriddenMembers; Assert.Equal(2, overriddenMembers.Length); Assert.Contains(baseIndexers[0], overriddenMembers); Assert.Contains(baseIndexers[1], overriddenMembers); } [Fact] public void IndexerAccessErrors() { var source = @"class C { public int this[int x, long y] { get { return x; } set { } } void M(C c) { c[0] = c[0, 0, 0]; //wrong number of arguments c[true, 1] = c[y: 1, x: long.MaxValue]; //wrong argument types c[1, x: 1] = c[x: 1, 2]; //bad mix of named and positional this[q: 1, r: 2] = base[0]; //bad parameter names / no indexer } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7_1).VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'C.this[int, long]' // c[0] = c[0, 0, 0]; //wrong number of arguments Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "c[0]").WithArguments("y", "C.this[int, long]").WithLocation(7, 9), // (7,16): error CS1501: No overload for method 'this' takes 3 arguments // c[0] = c[0, 0, 0]; //wrong number of arguments Diagnostic(ErrorCode.ERR_BadArgCount, "c[0, 0, 0]").WithArguments("this", "3").WithLocation(7, 16), // (8,11): error CS1503: Argument 1: cannot convert from 'bool' to 'int' // c[true, 1] = c[y: 1, x: long.MaxValue]; //wrong argument types Diagnostic(ErrorCode.ERR_BadArgType, "true").WithArguments("1", "bool", "int").WithLocation(8, 11), // (8,33): error CS1503: Argument 2: cannot convert from 'long' to 'int' // c[true, 1] = c[y: 1, x: long.MaxValue]; //wrong argument types Diagnostic(ErrorCode.ERR_BadArgType, "long.MaxValue").WithArguments("2", "long", "int").WithLocation(8, 33), // (9,14): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // c[1, x: 1] = c[x: 1, 2]; //bad mix of named and positional Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(9, 14), // (9,30): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // c[1, x: 1] = c[x: 1, 2]; //bad mix of named and positional Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "2").WithArguments("7.2").WithLocation(9, 30), // (10,14): error CS1739: The best overload for 'this' does not have a parameter named 'q' // this[q: 1, r: 2] = base[0]; //bad parameter names / no indexer Diagnostic(ErrorCode.ERR_BadNamedArgument, "q").WithArguments("this", "q").WithLocation(10, 14), // (10,28): error CS0021: Cannot apply indexing with [] to an expression of type 'object' // this[q: 1, r: 2] = base[0]; //bad parameter names / no indexer Diagnostic(ErrorCode.ERR_BadIndexLHS, "base[0]").WithArguments("object").WithLocation(10, 28) ); } [Fact] public void OverloadResolutionOnIndexersNotAccessors() { var source = @"class C { public int this[int x] { set { } } public int this[int x, double d = 1] { get { return x; } set { } } void M(C c) { int x = c[0]; //pick the first overload, even though it has no getter and the second would work } }"; CreateCompilation(source).VerifyDiagnostics( // (8,17): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "c[0]").WithArguments("C.this[int]")); } [Fact] public void UseExplicitInterfaceImplementationAccessor() { var source = @"interface I { int this[int x] { get; } } class C : I { int I.this[int x] { get { return x; } } void M(C c) { int x = c[0]; // no indexer found int y = ((I)c)[0]; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,17): error CS0021: Cannot apply indexing with [] to an expression of type 'C' Diagnostic(ErrorCode.ERR_BadIndexLHS, "c[0]").WithArguments("C")); } [Fact] public void UsePropertyAndAccessorsDirectly() { var source = @"class C { int this[int x] { get { return x; } set { } } void M(C c) { int x = c.Item[1]; //CS1061 - no such member int y = c.get_Item(1); //CS0571 - use the indexer c.set_Item(y); //CS0571 - use the indexer } }"; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS1061: 'C' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item").WithArguments("C", "Item"), // (8,19): error CS0571: 'C.this[int].get': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("C.this[int].get"), // (9,11): error CS0571: 'C.this[int].set': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Item").WithArguments("C.this[int].set")); } [Fact] public void NestedIndexerAccesses() { var source = @"class C { C this[int x] { get { return this; } set { } } int[] this[char x] { get { return null; } set { } } void M(C c) { int x = c[0][1][2][3]['a'][1]; //fine } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void NamedParameters() { var source = @"class C { int this[int x, string y, char z] { get { return x; } } void M(C c) { int x; x = c[x: 0, y: ""hello"", z:'a']; x = c[0, y: ""hello"", z:'a']; x = c[0, ""hello"", z:'a']; x = c[0, ""hello"", 'a']; x = c[z: 'a', x: 0, y: ""hello""]; //all reordered x = c[0, z:'a', y: ""hello""]; //some reordered } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void OptionalParameters() { var source = @"class C { int this[int x = 1, string y = ""goodbye"", char z = 'b'] { get { return x; } } void M(C c) { int x; x = this[]; //CS0443 - can't omit all x = c[x: 0]; x = c[y: ""hello""]; x = c[z:'a']; x = c[x: 0, y: ""hello""]; x = c[x: 0, z:'a']; x = c[y: ""hello"", z:'a']; x = c[x: 0, y: ""hello"", z:'a']; } }"; CreateCompilation(source).VerifyDiagnostics( // (8,18): error CS0443: Syntax error; value expected Diagnostic(ErrorCode.ERR_ValueExpected, "]")); } [Fact] public void ParameterArray() { var source = @"class C { int this[params int[] args] { get { return 0; } } int this[char c, params char[] args] { get { return 0; } } void M(C c) { int x; x = this[]; //CS0443 - can't omit all x = c[0]; x = c[0, 1]; x = c[0, 1, 2]; x = c[new int[3]]; x = c[args: new int[3]]; x = c['a']; x = c['a', 'b']; x = c['a', 'b', 'c']; x = c['a', new char[3]]; x = c['a', args: new char[3]]; x = c[args: new char[3], c: 'a']; } }"; CreateCompilation(source).VerifyDiagnostics( // (9,18): error CS0443: Syntax error; value expected Diagnostic(ErrorCode.ERR_ValueExpected, "]")); } [Fact] public void StaticIndexer() { var source = @"class C { // Illegal, but we shouldn't blow up public static int this[char c] { get { return 0; } } //CS0106 - illegal modifier public static void Main() { int x = C['a']; //CS0119 - can't use a type here int y = new C()['a']; //we don't even check for this kind of error because it's always cascading } }"; CreateCompilation(source).VerifyDiagnostics( // (4,23): error CS0106: The modifier 'static' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(4, 23), // (8,17): error CS0119: 'C' is a 'type', which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "C").WithArguments("C", "type").WithLocation(8, 17)); } [Fact] public void OverridingAndHidingWithExplicitIndexerName() { var source = @"using System; using System.Runtime.CompilerServices; public class A { public virtual int this[int x] { get { Console.WriteLine(""A""); return 0; } } } public class B : A { [IndexerName(""NotItem"")] public int this[int x] { get { Console.WriteLine(""B""); return 0; } } } public class C : B { public override int this[int x] { get { Console.WriteLine(""C""); return 0; } } }"; // Doesn't matter that B's indexer has an explicit name - the symbols are all called "this[]". CreateCompilation(source).VerifyDiagnostics( // (19,16): warning CS0114: 'B.this[int]' hides inherited member 'A.this[int]'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "this").WithArguments("B.this[int]", "A.this[int]"), // (31,25): error CS0506: 'C.this[int]': cannot override inherited member 'B.this[int]' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "this").WithArguments("C.this[int]", "B.this[int]")); } [ClrOnlyFact] public void CanBeReferencedByName() { var source = @" interface I { event System.Action E; int P { get; set; } int this[int x] { set; } } class C : I { event System.Action I.E { add { } remove { } } public event System.Action E; int I.P { get; set; } public int P { get; set; } int I.this[int x] { set { } } public int this[int x] { set { } } } "; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var globalNamespace = module.GlobalNamespace; var compilation = module.DeclaringCompilation; Assert.Equal(isFromSource, compilation != null); //// Source interface var @interface = globalNamespace.GetMember<NamedTypeSymbol>("I"); if (isFromSource) { Assert.True(@interface.IsFromCompilation(compilation)); } var interfaceEvent = @interface.GetMember<EventSymbol>("E"); var interfaceProperty = @interface.GetMember<PropertySymbol>("P"); var interfaceIndexer = @interface.Indexers.Single(); Assert.True(interfaceEvent.CanBeReferencedByName); Assert.True(interfaceProperty.CanBeReferencedByName); Assert.False(interfaceIndexer.CanBeReferencedByName); //// Source class var @class = globalNamespace.GetMember<NamedTypeSymbol>("C"); if (isFromSource) { Assert.True(@class.IsFromCompilation(compilation)); } var classEventImpl = @class.GetMembers().Where(m => m.GetExplicitInterfaceImplementations().Contains(interfaceEvent)).Single(); var classPropertyImpl = @class.GetMembers().Where(m => m.GetExplicitInterfaceImplementations().Contains(interfaceProperty)).Single(); var classIndexerImpl = @class.GetMembers().Where(m => m.GetExplicitInterfaceImplementations().Contains(interfaceIndexer)).Single(); Assert.False(classEventImpl.CanBeReferencedByName); Assert.False(classPropertyImpl.CanBeReferencedByName); Assert.False(classIndexerImpl.CanBeReferencedByName); var classEvent = @class.GetMember<EventSymbol>("E"); var classProperty = @class.GetMember<PropertySymbol>("P"); var classIndexer = @class.Indexers.Single(); Assert.True(classEvent.CanBeReferencedByName); Assert.True(classProperty.CanBeReferencedByName); Assert.False(classIndexer.CanBeReferencedByName); }; CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] public void RegressFinalValidationAssert() { var source = @"class C { int this[int x] { get { return x; } } void M() { System.Console.WriteLine(this[0]); } }"; CreateCompilation(source).VerifyDiagnostics(); } /// <summary> /// The Name and IsIndexer bits of explicitly implemented interface indexers do not roundtrip. /// This is unfortunate, but less so that having something declared with an IndexerDeclarationSyntax /// return false for IsIndexer. /// </summary> [ClrOnlyFact] public void ExplicitInterfaceImplementationIndexers() { var text = @" public interface I { int this[int x] { set; } } public class C : I { int I.this[int x] { set { } } } "; Action<ModuleSymbol> sourceValidator = module => { var globalNamespace = module.GlobalNamespace; var classC = globalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.Equal(0, classC.Indexers.Length); //excludes explicit implementations var classCIndexer = classC.GetMembers().Where(s => s.Kind == SymbolKind.Property).Single(); Assert.Equal("I.this[]", classCIndexer.Name); //interface name + WellKnownMemberNames.Indexer Assert.True(classCIndexer.IsIndexer()); //since declared with IndexerDeclarationSyntax }; Action<ModuleSymbol> metadataValidator = module => { var globalNamespace = module.GlobalNamespace; var classC = globalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.Equal(0, classC.Indexers.Length); //excludes explicit implementations var classCIndexer = classC.GetMembers().Where(s => s.Kind == SymbolKind.Property).Single(); Assert.Equal("I.Item", classCIndexer.Name); //name does not reflect WellKnownMemberNames.Indexer Assert.False(classCIndexer.IsIndexer()); //not the default member of C }; CompileAndVerify(text, sourceSymbolValidator: sourceValidator, symbolValidator: metadataValidator); } [Fact] public void NoAutoIndexers() { var source = @"class B { public virtual int this[int x] { get; set; } }"; CreateCompilation(source).VerifyDiagnostics( // (3,38): error CS0501: 'B.this[int].get' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("B.this[int].get"), // (3,43): error CS0501: 'B.this[int].set' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("B.this[int].set")); } [Fact] public void BaseIndexerAccess() { var source = @"public class Base { public int this[int x] { get { return x; } } } public class Derived : Base { public new int this[int x] { get { return x; } } void Method() { int x = base[1]; } }"; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var indexerAccessSyntax = GetElementAccessExpressions(tree.GetCompilationUnitRoot()).Single(); var baseClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var baseIndexer = baseClass.Indexers.Single(); // Confirm that the base indexer is used (even though the derived indexer signature matches). var model = comp.GetSemanticModel(tree); var symbolInfo = model.GetSymbolInfo(indexerAccessSyntax); Assert.Equal(baseIndexer.GetPublicSymbol(), symbolInfo.Symbol); } /// <summary> /// Indexers cannot have ref params in source, but they can in metadata. /// </summary> [Fact] public void IndexerWithRefParameter_Access() { var source = @" class Test { static void Main() { RefIndexer r = new RefIndexer(); int x = 1; x = r[ref x]; r[ref x] = 1; r[ref x]++; r[ref x] += 2; } } "; var compilation = CreateCompilation(source, new[] { TestReferences.SymbolsTests.Indexers }); compilation.VerifyDiagnostics( // (8,13): error CS1545: Property, indexer, or event 'RefIndexer.this[ref int]' is not supported by the language; try directly calling accessor methods 'RefIndexer.get_Item(ref int)' or 'RefIndexer.set_Item(ref int, int)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "r[ref x]").WithArguments("RefIndexer.this[ref int]", "RefIndexer.get_Item(ref int)", "RefIndexer.set_Item(ref int, int)"), // (9,9): error CS1545: Property, indexer, or event 'RefIndexer.this[ref int]' is not supported by the language; try directly calling accessor methods 'RefIndexer.get_Item(ref int)' or 'RefIndexer.set_Item(ref int, int)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "r[ref x]").WithArguments("RefIndexer.this[ref int]", "RefIndexer.get_Item(ref int)", "RefIndexer.set_Item(ref int, int)"), // (10,9): error CS1545: Property, indexer, or event 'RefIndexer.this[ref int]' is not supported by the language; try directly calling accessor methods 'RefIndexer.get_Item(ref int)' or 'RefIndexer.set_Item(ref int, int)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "r[ref x]").WithArguments("RefIndexer.this[ref int]", "RefIndexer.get_Item(ref int)", "RefIndexer.set_Item(ref int, int)"), // (11,9): error CS1545: Property, indexer, or event 'RefIndexer.this[ref int]' is not supported by the language; try directly calling accessor methods 'RefIndexer.get_Item(ref int)' or 'RefIndexer.set_Item(ref int, int)' Diagnostic(ErrorCode.ERR_BindToBogusProp2, "r[ref x]").WithArguments("RefIndexer.this[ref int]", "RefIndexer.get_Item(ref int)", "RefIndexer.set_Item(ref int, int)")); } /// <summary> /// Indexers cannot have ref params in source, but they can in metadata. /// </summary> [Fact] public void IndexerWithRefParameter_CallAccessor() { var source = @" class Test { static void Main() { RefIndexer r = new RefIndexer(); int x = 1; x = r.get_Item(ref x); r.set_Item(ref x, 1); } } "; var compilation = CreateCompilation(source, new[] { TestReferences.SymbolsTests.Indexers }); compilation.VerifyDiagnostics(); } /// <summary> /// Indexers cannot have ref params in source, but they can in metadata. /// </summary> [Fact] public void IndexerWithRefParameter_Override() { var source = @" class Test : RefIndexer { public override int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilation(source, new MetadataReference[] { TestReferences.SymbolsTests.Indexers }); compilation.VerifyDiagnostics( // (4,25): error CS0115: 'Test.this[int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Test.this[int]")); } /// <summary> /// Indexers cannot have ref params in source, but they can in metadata. /// </summary> [Fact] public void IndexerWithRefParameter_ImplicitlyImplement() { var source = @" class Test : IRefIndexer { public int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilation(source, new[] { TestReferences.SymbolsTests.Indexers }); // Normally, we wouldn't see errors for the accessors, but here we do because the indexer is bogus. compilation.VerifyDiagnostics( // (2,7): error CS0535: 'Test' does not implement interface member 'IRefIndexer.get_Item(ref int)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IRefIndexer").WithArguments("Test", "IRefIndexer.get_Item(ref int)"), // (2,7): error CS0535: 'Test' does not implement interface member 'IRefIndexer.set_Item(ref int, int)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IRefIndexer").WithArguments("Test", "IRefIndexer.set_Item(ref int, int)")); } /// <summary> /// Indexers cannot have ref params in source, but they can in metadata. /// </summary> [Fact] public void IndexerWithRefParameter_ExplicitlyImplement() { var source = @" class Test : IRefIndexer { int IRefIndexer.this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilation(source, new MetadataReference[] { TestReferences.SymbolsTests.Indexers }); // Normally, we wouldn't see errors for the accessors, but here we do because the indexer is bogus. compilation.VerifyDiagnostics( // (4,21): error CS0539: 'Test.this[int]' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Test.this[int]"), // (2,7): error CS0535: 'Test' does not implement interface member 'IRefIndexer.get_Item(ref int)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IRefIndexer").WithArguments("Test", "IRefIndexer.get_Item(ref int)"), // (2,7): error CS0535: 'Test' does not implement interface member 'IRefIndexer.set_Item(ref int, int)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IRefIndexer").WithArguments("Test", "IRefIndexer.set_Item(ref int, int)")); } [Fact] public void IndexerNameAttribute() { var source = @" using System.Runtime.CompilerServices; class B { [IndexerName(""A"")] public virtual int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").Indexers.Single(); Assert.Equal(WellKnownMemberNames.Indexer, indexer.Name); Assert.Equal("A", indexer.MetadataName); Assert.Equal("get_A", indexer.GetMethod.Name); Assert.Equal("get_A", indexer.GetMethod.MetadataName); Assert.Equal("set_A", indexer.SetMethod.Name); Assert.Equal("set_A", indexer.SetMethod.MetadataName); } [WorkItem(528830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528830")] [Fact(Skip = "528830")] public void EscapedIdentifierInIndexerNameAttribute() { var source = @" using System.Runtime.CompilerServices; interface I { [IndexerName(""@indexer"")] int this[int x] { get; set; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I").Indexers.Single(); Assert.Equal("@indexer", indexer.MetadataName); Assert.Equal("get_@indexer", indexer.GetMethod.MetadataName); Assert.Equal("set_@indexer", indexer.SetMethod.MetadataName); } [Fact] public void NameNotCopiedOnOverride1() { var source = @" using System.Runtime.CompilerServices; class B { [IndexerName(""A"")] public virtual int this[int x] { get { return 0; } set { } } } class D : B { public override int this[int x] { get { return 0; } set { } } [IndexerName(""A"")] //error since name isn't copied down to override public int this[int x, int y] { get { return 0; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (15,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } [Fact] public void NameNotCopiedOnOverride2() { var source = @" using System.Runtime.CompilerServices; class B { [IndexerName(""A"")] public virtual int this[int x] { get { return 0; } set { } } } class D : B { [IndexerName(""A"")] //dev10 didn't allow this, but it should eliminate the error public override int this[int x] { get { return 0; } set { } } [IndexerName(""A"")] //error since name isn't copied down to override public int this[int x, int y] { get { return 0; } set { } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var derivedType = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("D"); Assert.True(derivedType.Indexers.All(i => i.MetadataName == "A")); } [Fact] public void NameNotCopiedOnOverride3() { var source = @" using System.Runtime.CompilerServices; class B { [IndexerName(""A"")] public virtual int this[int x] { get { return 0; } set { } } } class D : B { public override int this[int x] { get { return 0; } set { } } // If the name of the overridden indexer was copied, this would be an error. public int this[int x, int y] { get { return 0; } set { } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void IndexerNameLookup1() { var source = @" using System.Runtime.CompilerServices; class A { public const string get_X = ""X""; } class B : A { [IndexerName(C.get_X)] public int this[int x] { get { return 0; } } } class C : B { [IndexerName(get_X)] public int this[int x, int y] { get { return 0; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var classA = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var classB = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B"); var classC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var get_XA = classA.GetMember<FieldSymbol>("get_X"); var get_XB = classB.GetMember<MethodSymbol>("get_X"); var get_XC = classC.GetMember<MethodSymbol>("get_X"); Assert.Equal("X", get_XB.AssociatedSymbol.MetadataName); Assert.Equal("X", get_XC.AssociatedSymbol.MetadataName); } [Fact] public void IndexerNameLookup2() { var source = @" using System.Runtime.CompilerServices; class A { public const string get_X = ""X""; [IndexerName(get_X)] public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,30): error CS0102: The type 'A' already contains a definition for 'get_X' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("A", "get_X")); var classA = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); Assert.Equal("X", classA.Indexers.Single().MetadataName); } [Fact] public void IndexerNameLookup3() { var source = @" using System.Runtime.CompilerServices; public class MyAttribute : System.Attribute { public MyAttribute(object o) { } } class A { [IndexerName(get_Item)] public int this[int x] { get { return 0; } } // Doesn't matter what attribute it is or what member it's on - can't see indexer members. [MyAttribute(get_Item)] int x; } "; // NOTE: Dev10 reports CS0571 for MyAttribute's use of get_Item var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,18): error CS0571: 'A.this[int].get': cannot explicitly call operator or accessor // [IndexerName(get_Item)] Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("A.this[int].get"), // (15,18): error CS0571: 'A.this[int].get': cannot explicitly call operator or accessor // [MyAttribute(get_Item)] Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("A.this[int].get"), // (16,9): warning CS0169: The field 'A.x' is never used // int x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("A.x")); } [Fact] public void IndexerNameLookup4() { var source = @" using System.Runtime.CompilerServices; class A { [IndexerName(B.get_Item)] public int this[int x] { get { return 0; } } } class B { [IndexerName(A.get_Item)] public int this[int x] { get { return 0; } } } "; // NOTE: Dev10 reports CS0117 in A, but CS0571 in B var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,20): error CS0571: 'B.this[int].get': cannot explicitly call operator or accessor // [IndexerName(B.get_Item)] Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("B.this[int].get"), // (12,20): error CS0571: 'A.this[int].get': cannot explicitly call operator or accessor // [IndexerName(A.get_Item)] Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("A.this[int].get")); } [Fact] public void IndexerNameLookup5() { var source = @" using System.Runtime.CompilerServices; class A { public const string get_Item = ""X""; } class B : A { public const string C = get_Item; [IndexerName(C)] public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [Fact] public void IndexerNameLookupClass() { var source = @" using System.Runtime.CompilerServices; class A { public const string Constant1 = B.Constant1; public const string Constant2 = B.Constant2; } class B { public const string Constant1 = ""X""; public const string Constant2 = A.Constant2; [IndexerName(A.Constant1)] public int this[int x] { get { return 0; } } [IndexerName(A.Constant2)] public int this[long x] { get { return 0; } } } "; // CONSIDER: this cascading is a bit verbose. CreateCompilation(source).VerifyDiagnostics( // (18,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(A.Constant2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "A.Constant2"), // (7,25): error CS0110: The evaluation of the constant value for 'A.Constant2' involves a circular definition // public const string Constant2 = B.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("A.Constant2"), // (19,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type // public int this[long x] { get { return 0; } } Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } [Fact] public void IndexerNameLookupStruct() { var source = @" using System.Runtime.CompilerServices; struct A { public const string Constant1 = B.Constant1; public const string Constant2 = B.Constant2; } struct B { public const string Constant1 = ""X""; public const string Constant2 = A.Constant2; [IndexerName(A.Constant1)] public int this[int x] { get { return 0; } } [IndexerName(A.Constant2)] public int this[long x] { get { return 0; } } } "; // CONSIDER: this cascading is a bit verbose. CreateCompilation(source).VerifyDiagnostics( // (18,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(A.Constant2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "A.Constant2"), // (13,25): error CS0110: The evaluation of the constant value for 'A.Constant2' involves a circular definition // public const string Constant2 = A.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("A.Constant2"), // (19,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type // public int this[long x] { get { return 0; } } Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } [Fact] public void IndexerNameLookupInterface() { var source = @" using System.Runtime.CompilerServices; interface A { const string Constant1 = B.Constant1; const string Constant2 = B.Constant2; } interface B { const string Constant1 = ""X""; const string Constant2 = A.Constant2; [IndexerName(A.Constant1)] int this[int x] { get; } [IndexerName(A.Constant2)] int this[long x] { get; } } "; // CONSIDER: this cascading is a bit verbose. CreateCompilation(source, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (18,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(A.Constant2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "A.Constant2").WithLocation(18, 18), // (7,18): error CS0110: The evaluation of the constant value for 'A.Constant2' involves a circular definition // const string Constant2 = B.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("A.Constant2").WithLocation(7, 18), // (19,9): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type // int this[long x] { get; } Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this").WithLocation(19, 9), // (12,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant1 = "X"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant1").WithArguments("default interface implementation", "8.0").WithLocation(12, 18), // (13,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant2 = A.Constant2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant2").WithArguments("default interface implementation", "8.0").WithLocation(13, 18), // (6,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant1 = B.Constant1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant1").WithArguments("default interface implementation", "8.0").WithLocation(6, 18), // (7,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant2 = B.Constant2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant2").WithArguments("default interface implementation", "8.0").WithLocation(7, 18) ); } [Fact] public void IndexerNameLookupGenericClass() { var source = @" using System.Runtime.CompilerServices; class A<T> { public const string Constant1 = B<string>.Constant1; public const string Constant2 = B<int>.Constant2; [IndexerName(B<byte>.Constant2)] public int this[long x] { get { return 0; } } } class B<T> { public const string Constant1 = ""X""; public const string Constant2 = A<bool>.Constant2; [IndexerName(A<char>.Constant1)] public int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (9,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(B<byte>.Constant2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "B<byte>.Constant2"), // (7,25): error CS0110: The evaluation of the constant value for 'A<T>.Constant2' involves a circular definition // public const string Constant2 = B<int>.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("A<T>.Constant2")); } [Fact] public void IndexerNameLookupGenericStruct() { var source = @" using System.Runtime.CompilerServices; struct A<T> { public const string Constant1 = B<string>.Constant1; public const string Constant2 = B<int>.Constant2; [IndexerName(B<byte>.Constant2)] public int this[long x] { get { return 0; } } } struct B<T> { public const string Constant1 = ""X""; public const string Constant2 = A<bool>.Constant2; [IndexerName(A<char>.Constant1)] public int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (9,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(B<byte>.Constant2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "B<byte>.Constant2"), // (7,25): error CS0110: The evaluation of the constant value for 'A<T>.Constant2' involves a circular definition // public const string Constant2 = B<int>.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("A<T>.Constant2")); } [Fact] public void IndexerNameLookupGenericInterface() { var source = @" using System.Runtime.CompilerServices; interface A<T> { const string Constant1 = B<string>.Constant1; const string Constant2 = B<int>.Constant2; [IndexerName(B<byte>.Constant2)] int this[long x] { get; } } interface B<T> { const string Constant1 = ""X""; const string Constant2 = A<bool>.Constant2; [IndexerName(A<char>.Constant1)] int this[int x] { get; } } "; CreateCompilation(source, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (9,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(B<byte>.Constant2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "B<byte>.Constant2").WithLocation(9, 18), // (7,18): error CS0110: The evaluation of the constant value for 'A<T>.Constant2' involves a circular definition // const string Constant2 = B<int>.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("A<T>.Constant2").WithLocation(7, 18), // (15,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant1 = "X"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant1").WithArguments("default interface implementation", "8.0").WithLocation(15, 18), // (16,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant2 = A<bool>.Constant2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant2").WithArguments("default interface implementation", "8.0").WithLocation(16, 18), // (6,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant1 = B<string>.Constant1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant1").WithArguments("default interface implementation", "8.0").WithLocation(6, 18), // (7,18): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // const string Constant2 = B<int>.Constant2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Constant2").WithArguments("default interface implementation", "8.0").WithLocation(7, 18) ); } [Fact] public void IndexerNameLookupTypeParameter() { var source = @" using System.Runtime.CompilerServices; class P { public const string Constant1 = Q.Constant1; public const string Constant2 = Q.Constant2; } class Q { public const string Constant1 = ""X""; public const string Constant2 = P.Constant2; } class A<T> where T : P { [IndexerName(T.Constant1)] public int this[long x] { get { return 0; } } } class B<T> where T : Q { [IndexerName(T.Constant2)] public int this[long x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (7,25): error CS0110: The evaluation of the constant value for 'P.Constant2' involves a circular definition // public const string Constant2 = Q.Constant2; Diagnostic(ErrorCode.ERR_CircConstValue, "Constant2").WithArguments("P.Constant2"), // (18,18): error CS0119: 'T' is a type parameter, which is not valid in the given context // [IndexerName(T.Constant1)] Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter"), // (24,18): error CS0119: 'T' is a type parameter, which is not valid in the given context // [IndexerName(T.Constant2)] Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter")); } [Fact] public void IndexerNameLookupEnum() { var source = @" using System.Runtime.CompilerServices; enum E { A, B, C = 6, D, E = F, F = E } class A { [IndexerName(E.A)] public int this[long x] { get { return 0; } } [IndexerName(E.B)] public int this[char x] { get { return 0; } } [IndexerName(E.C)] public int this[bool x] { get { return 0; } } [IndexerName(E.D)] public int this[uint x] { get { return 0; } } [IndexerName(E.E)] public int this[byte x] { get { return 0; } } [IndexerName(E.F)] public int this[ulong x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,5): error CS0110: The evaluation of the constant value for 'E.E' involves a circular definition // E = F, Diagnostic(ErrorCode.ERR_CircConstValue, "E").WithArguments("E.E"), // (16,18): error CS1503: Argument 1: cannot convert from 'E' to 'string' // [IndexerName(E.A)] Diagnostic(ErrorCode.ERR_BadArgType, "E.A").WithArguments("1", "E", "string"), // (19,18): error CS1503: Argument 1: cannot convert from 'E' to 'string' // [IndexerName(E.B)] Diagnostic(ErrorCode.ERR_BadArgType, "E.B").WithArguments("1", "E", "string"), // (22,18): error CS1503: Argument 1: cannot convert from 'E' to 'string' // [IndexerName(E.C)] Diagnostic(ErrorCode.ERR_BadArgType, "E.C").WithArguments("1", "E", "string"), // (25,18): error CS1503: Argument 1: cannot convert from 'E' to 'string' // [IndexerName(E.D)] Diagnostic(ErrorCode.ERR_BadArgType, "E.D").WithArguments("1", "E", "string"), // (28,18): error CS1503: Argument 1: cannot convert from 'E' to 'string' // [IndexerName(E.E)] Diagnostic(ErrorCode.ERR_BadArgType, "E.E").WithArguments("1", "E", "string"), // (31,18): error CS1503: Argument 1: cannot convert from 'E' to 'string' // [IndexerName(E.F)] Diagnostic(ErrorCode.ERR_BadArgType, "E.F").WithArguments("1", "E", "string")); } [Fact] public void IndexerNameLookupProperties() { var source = @" using System.Runtime.CompilerServices; class A { internal static string Name { get { return ""A""; } } [IndexerName(B.Name)] public int this[int x] { get { return 0; } } } class B { internal static string Name { get { return ""B""; } } [IndexerName(A.Name)] public int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (13,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(A.Name)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "A.Name"), // (7,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(B.Name)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "B.Name")); } [Fact] public void IndexerNameLookupCalls() { var source = @" using System.Runtime.CompilerServices; class A { internal static string GetName() { return ""A""; } [IndexerName(B.GetName())] public int this[int x] { get { return 0; } } } class B { internal static string GetName() { return ""B""; } [IndexerName(A.GetName())] public int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (7,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(B.GetName())] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "B.GetName()"), // (13,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(A.GetName())] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "A.GetName()")); } [Fact] public void IndexerNameLookupNonExistent() { var source = @" using System.Runtime.CompilerServices; class A { [IndexerName(B.Fake)] public int this[int x] { get { return 0; } } } class B { [IndexerName(A.Fake)] public int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (11,20): error CS0117: 'A' does not contain a definition for 'Fake' // [IndexerName(A.Fake)] Diagnostic(ErrorCode.ERR_NoSuchMember, "Fake").WithArguments("A", "Fake"), // (6,20): error CS0117: 'B' does not contain a definition for 'Fake' // [IndexerName(B.Fake)] Diagnostic(ErrorCode.ERR_NoSuchMember, "Fake").WithArguments("B", "Fake")); } [Fact] public void IndexerNameNotEmitted() { var source = @" using System.Runtime.CompilerServices; class Program { [IndexerName(""A"")] public int this[int x] { get { return 0; } set { } } } "; var compilation = CreateCompilation(source).VerifyDiagnostics(); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").Indexers.Single(); Assert.True(indexer.IsIndexer); Assert.Equal("A", indexer.MetadataName); Assert.True(indexer.GetAttributes().Single().IsTargetAttribute(indexer, AttributeDescription.IndexerNameAttribute)); CompileAndVerify(compilation, symbolValidator: module => { var peIndexer = (PEPropertySymbol)module.GlobalNamespace.GetTypeMember("Program").Indexers.Single(); Assert.True(peIndexer.IsIndexer); Assert.Equal("A", peIndexer.MetadataName); Assert.Empty(peIndexer.GetAttributes()); Assert.Empty(((PEModuleSymbol)module).GetCustomAttributesForToken(peIndexer.Handle)); }); } [WorkItem(545884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545884")] [Fact] public void IndexerNameDeadlock1() { var source = @" using System.Runtime.CompilerServices; class A { public const string Name = ""A""; [IndexerName(B.Name)] public int this[int x] { get { return 0; } } } class B { public const string Name = ""B""; [IndexerName(A.Name)] public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilation(source); var loopResult = Parallel.ForEach(compilation.GlobalNamespace.GetTypeMembers(), type => type.ForceComplete(null, default(CancellationToken))); Assert.True(loopResult.IsCompleted); compilation.VerifyDiagnostics(); } [WorkItem(545884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545884")] [Fact] public void IndexerNameDeadlock2() { var source = @" using System.Runtime.CompilerServices; class A { private const string Name = ""A""; [IndexerName(B.Name)] public int this[int x] { get { return 0; } } } class B { private const string Name = ""B""; [IndexerName(A.Name)] public int this[int x] { get { return 0; } } } "; var compilation = CreateCompilation(source); var loopResult = Parallel.ForEach(compilation.GlobalNamespace.GetTypeMembers(), type => type.ForceComplete(null, default(CancellationToken))); Assert.True(loopResult.IsCompleted); compilation.VerifyDiagnostics( // (7,20): error CS0122: 'B.Name' is inaccessible due to its protection level // [IndexerName(B.Name)] Diagnostic(ErrorCode.ERR_BadAccess, "Name").WithArguments("B.Name"), // (14,20): error CS0122: 'A.Name' is inaccessible due to its protection level // [IndexerName(A.Name)] Diagnostic(ErrorCode.ERR_BadAccess, "Name").WithArguments("A.Name")); } [Fact] public void OverloadResolutionPrecedence() { var source = @"public class C { public int this[int x] { get { return 0; } } public int this[int x, int y = 1] { get { return 0; } } public int this[params int[] x] { get { return 0; } } void Method() { int x; x = this[1]; x = this[1, 2]; x = this[1, 2, 3]; x = this[new int[1]]; } }"; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); CheckOverloadResolutionResults(tree, model, "System.Int32 C.this[System.Int32 x] { get; }", "System.Int32 C.this[System.Int32 x, [System.Int32 y = 1]] { get; }", "System.Int32 C.this[params System.Int32[] x] { get; }", "System.Int32 C.this[params System.Int32[] x] { get; }"); } [Fact] public void OverloadResolutionOverriding() { var source = @"public class Base { public virtual int this[int x] { get { return 0; } } public virtual int this[int x, int y = 1] { get { return 0; } } public virtual int this[params int[] x] { get { return 0; } } } public class Derived : Base { public override int this[int x] { get { return 0; } } public override int this[int x, int y = 1] { get { return 0; } } public override int this[params int[] x] { get { return 0; } } void Method() { int x; x = this[1]; x = this[1, 2]; x = this[1, 2, 3]; x = base[1]; x = base[1, 2]; x = base[1, 2, 3]; } }"; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); CheckOverloadResolutionResults(tree, model, // NOTE: we'll actually emit calls to the corresponding base indexers "System.Int32 Derived.this[System.Int32 x] { get; }", "System.Int32 Derived.this[System.Int32 x, [System.Int32 y = 1]] { get; }", "System.Int32 Derived.this[params System.Int32[] x] { get; }", "System.Int32 Base.this[System.Int32 x] { get; }", "System.Int32 Base.this[System.Int32 x, [System.Int32 y = 1]] { get; }", "System.Int32 Base.this[params System.Int32[] x] { get; }"); } [Fact] public void OverloadResolutionFallbackInBase() { var source = @"public class Base { public int this[params int[] x] { get { return 0; } } } public class Derived : Base { public int this[int x] { get { return 0; } } public int this[int x, int y = 1] { get { return 0; } } void Method() { int x; x = this[1]; x = this[1, 2]; x = this[1, 2, 3]; x = base[1]; x = base[1, 2]; x = base[1, 2, 3]; } }"; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); CheckOverloadResolutionResults(tree, model, "System.Int32 Derived.this[System.Int32 x] { get; }", "System.Int32 Derived.this[System.Int32 x, [System.Int32 y = 1]] { get; }", "System.Int32 Base.this[params System.Int32[] x] { get; }", "System.Int32 Base.this[params System.Int32[] x] { get; }", "System.Int32 Base.this[params System.Int32[] x] { get; }", "System.Int32 Base.this[params System.Int32[] x] { get; }"); } [Fact] public void OverloadResolutionDerivedRemovesParamsModifier() { var source = @"abstract class Base { public abstract int this[Derived c1, Derived c2, params Derived[] c3] { get; } } class Derived : Base { public override int this[Derived C1, Derived C2, Derived[] C3] { get { return 0; } } //removes 'params' } class Test2 { public static void Main2() { Derived d = new Derived(); Base b = d; int x; x = b[d, d, d, d, d]; // Fine x = d[d, d, d, d, d]; // Fine } }"; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); CheckOverloadResolutionResults(tree, model, "System.Int32 Base.this[Derived c1, Derived c2, params Derived[] c3] { get; }", "System.Int32 Derived.this[Derived C1, Derived C2, params Derived[] C3] { get; }"); } [Fact] public void OverloadResolutionDerivedAddsParamsModifier() { var source = @"abstract class Base { public abstract int this[Derived c1, Derived c2, Derived[] c3] { get; } } class Derived : Base { public override int this[Derived C1, Derived C2, params Derived[] C3] { get { return 0; } } //adds 'params' } class Test2 { public static void Main2() { Derived d = new Derived(); Base b = d; int x; x = b[d, d, d, d, d]; // CS1501 x = d[d, d, d, d, d]; // CS1501 } }"; CreateCompilation(source).VerifyDiagnostics( // (16,13): error CS1501: No overload for method 'this' takes 5 arguments Diagnostic(ErrorCode.ERR_BadArgCount, "b[d, d, d, d, d]").WithArguments("this", "5"), // (17,13): error CS1501: No overload for method 'this' takes 5 arguments Diagnostic(ErrorCode.ERR_BadArgCount, "d[d, d, d, d, d]").WithArguments("this", "5")); } [WorkItem(542747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542747")] [Fact()] public void IndexerAccessorParameterIsSynthesized() { var text = @" struct Test { public byte this[byte p] { get { return p; } } } "; var comp = CreateCompilation(text); NamedTypeSymbol type01 = comp.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single(); var indexer = type01.GetMembers(WellKnownMemberNames.Indexer).Single() as PropertySymbol; Assert.NotNull(indexer.GetMethod); Assert.False(indexer.GetMethod.Parameters.IsEmpty); // VB is SynthesizedParameterSymbol; C# is SourceComplexParameterSymbol foreach (var p in indexer.GetMethod.Parameters) { Assert.True(p.IsImplicitlyDeclared, "Parameter of Indexer Accessor"); } } [WorkItem(542831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542831")] [Fact] public void ProtectedBaseIndexer() { var text = @" public class Base { protected int this[int index] { get { return 0; } } } public class Derived : Base { public int M() { return base[0]; } } "; CreateCompilation(text).VerifyDiagnostics(); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void SameSignaturesDifferentNames() { var ilSource = @" .class public auto ansi beforefieldinit SameSignaturesDifferentNames extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('Accessor1')} .method public hidebysig specialname instance int32 Accessor1(int32 x, int64 y) cil managed { ldc.i4.0 ret } .method public hidebysig specialname instance void Accessor2(int32 x, int64 y, int32 'value') cil managed { ret } .method public hidebysig specialname instance void Accessor3(int32 x, int64 y, int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance int32 Indexer1(int32, int64) { .get instance int32 SameSignaturesDifferentNames::Accessor1(int32, int64) .set instance void SameSignaturesDifferentNames::Accessor2(int32, int64, int32) } .property instance int32 Indexer2(int32, int64) { .get instance int32 SameSignaturesDifferentNames::Accessor1(int32, int64) .set instance void SameSignaturesDifferentNames::Accessor3(int32, int64, int32) } }"; var cSharpSource = @" class Test { static void Main() { SameSignaturesDifferentNames s = new SameSignaturesDifferentNames(); System.Console.WriteLine(s[0, 1]); } } "; CreateCompilationWithILAndMscorlib40(cSharpSource, ilSource).VerifyDiagnostics( // (7,34): error CS0121: The call is ambiguous between the following methods or properties: 'SameSignaturesDifferentNames.this[int, long]' and 'SameSignaturesDifferentNames.this[int, long]' Diagnostic(ErrorCode.ERR_AmbigCall, "s[0, 1]").WithArguments("SameSignaturesDifferentNames.this[int, long]", "SameSignaturesDifferentNames.this[int, long]")); } [WorkItem(543261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543261")] [ClrOnlyFact] public void OverrideOneAccessorOnly() { var source = @"class A { public virtual object this[object index] { get { return null; } set { } } } class B1 : A { public override object this[object index] { get { return base[index]; } } } class B2 : A { public override object this[object index] { set { base[index] = value; } } } class C { static void M(B1 _1, B2 _2) { _1[null] = _1[null]; _2[null] = _2[null]; } }"; CompileAndVerify(source); } private static void CheckOverloadResolutionResults(SyntaxTree tree, SemanticModel model, params string[] expected) { var actual = GetElementAccessExpressions(tree.GetCompilationUnitRoot()).Select(syntax => model.GetSymbolInfo(syntax).Symbol.ToTestDisplayString()); AssertEx.Equal(expected, actual, itemInspector: s => string.Format("\"{0}\"", s)); } private static IEnumerable<ElementAccessExpressionSyntax> GetElementAccessExpressions(SyntaxNode node) { return node == null ? SpecializedCollections.EmptyEnumerable<ElementAccessExpressionSyntax>() : node.DescendantNodesAndSelf().Where(s => s.IsKind(SyntaxKind.ElementAccessExpression)).Cast<ElementAccessExpressionSyntax>(); } [Fact] public void PartialType() { var text1 = @" partial class C { public int this[int x] { get { return 0; } set { } } }"; var text2 = @" partial class C { public void M() {} } "; var compilation = CreateCompilation(new string[] { text1, text2 }); Assert.True(((TypeSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single()).GetMembers().Any(x => x.IsIndexer())); //test with text inputs reversed in case syntax ordering predicate ever changes. compilation = CreateCompilation(new string[] { text2, text1 }); Assert.True(((TypeSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single()).GetMembers().Any(x => x.IsIndexer())); } [WorkItem(543957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543957")] [Fact] public void SemanticModelIndexerGroupHiding() { var source = @"public class Base { public int this[int x] { get { return x; } } public virtual int this[int x, int y] { get { return x; } } public int this[int x, int y, int z] { get { return x; } } } public class Derived : Base { public new int this[int x] { get { return x; } } public override int this[int x, int y] { get { return x; } } void Method() { int x; x = this[1]; x = base[1]; Derived d = new Derived(); x = d[1]; Base b = new Base(); x = b[1]; Wrapper w = new Wrapper(); x = w.Base[1]; x = w.Derived[1]; x = (d ?? w.Derived)[1]; } } public class Wrapper { public Base Base; public Derived Derived; } "; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); var elementAccessSyntaxes = GetElementAccessExpressions(tree.GetCompilationUnitRoot()); // The access itself doesn't have an indexer group. foreach (var syntax in elementAccessSyntaxes) { Assert.Equal(0, model.GetIndexerGroup(syntax).Length); } var baseType = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var derivedType = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var baseIndexers = baseType.Indexers; var derivedIndexers = derivedType.Indexers; var baseIndexer3 = baseIndexers.Single(indexer => indexer.ParameterCount == 3); var baseIndexerGroup = baseIndexers; var derivedIndexerGroup = derivedIndexers.Concat(ImmutableArray.Create<PropertySymbol>(baseIndexer3)); var receiverSyntaxes = elementAccessSyntaxes.Select(access => access.Expression); Assert.Equal(7, receiverSyntaxes.Count()); // The receiver of each access expression has an indexer group. foreach (var syntax in receiverSyntaxes) { var type = model.GetTypeInfo(syntax).Type.GetSymbol(); Assert.NotNull(type); var indexerGroup = model.GetIndexerGroup(syntax); if (type.Equals(baseType)) { Assert.True(indexerGroup.SetEquals(baseIndexerGroup.GetPublicSymbols(), EqualityComparer<IPropertySymbol>.Default)); } else if (type.Equals(derivedType)) { Assert.True(indexerGroup.SetEquals(derivedIndexerGroup.GetPublicSymbols(), EqualityComparer<IPropertySymbol>.Default)); } else { Assert.True(false, "Unexpected type " + type.ToTestDisplayString()); } } } [WorkItem(543957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543957")] [Fact] public void SemanticModelIndexerGroupAccessibility() { var source = @"class Base { private int this[int x] { get { return 0; } } protected int this[string x] { get { return 0; } } public int this[bool x] { get { return 0; } } void M() { int x; x = this[1]; //all } } class Derived1 : Base { void M() { int x; x = this[""string""]; //public and protected Derived2 d = new Derived2(); x = d[true]; //only public } } class Derived2 : Base { } "; var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); var elementAccessSyntaxes = GetElementAccessExpressions(tree.GetCompilationUnitRoot()); // The access itself doesn't have an indexer group. foreach (var syntax in elementAccessSyntaxes) { Assert.Equal(0, model.GetIndexerGroup(syntax).Length); } var baseType = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); var derived1Type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived1"); var derived2Type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived2"); var indexers = baseType.Indexers; var publicIndexer = indexers.Single(indexer => indexer.DeclaredAccessibility == Accessibility.Public); var protectedIndexer = indexers.Single(indexer => indexer.DeclaredAccessibility == Accessibility.Protected); var privateIndexer = indexers.Single(indexer => indexer.DeclaredAccessibility == Accessibility.Private); var receiverSyntaxes = elementAccessSyntaxes.Select(access => access.Expression).ToArray(); Assert.Equal(3, receiverSyntaxes.Length); // In declaring type, can see everything. Assert.True(model.GetIndexerGroup(receiverSyntaxes[0]).SetEquals( ImmutableArray.Create<PropertySymbol>(publicIndexer, protectedIndexer, privateIndexer).GetPublicSymbols(), EqualityComparer<IPropertySymbol>.Default)); // In subtype of declaring type, can see non-private. Assert.True(model.GetIndexerGroup(receiverSyntaxes[1]).SetEquals( ImmutableArray.Create<PropertySymbol>(publicIndexer, protectedIndexer).GetPublicSymbols(), EqualityComparer<IPropertySymbol>.Default)); // In subtype of declaring type, can only see public (or internal) members of other subtypes. Assert.True(model.GetIndexerGroup(receiverSyntaxes[2]).SetEquals( ImmutableArray.Create<PropertySymbol>(publicIndexer).GetPublicSymbols(), EqualityComparer<IPropertySymbol>.Default)); } [WorkItem(545851, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545851")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void DistinctOptionalParameterValues() { var source1 = @".class abstract public A { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')} .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance int32 get_P(int32 x, [opt] int32 y) { .param[2] = int32(1) } .method public abstract virtual instance void set_P(int32 x, [opt] int32 y, int32 v) { .param[2] = int32(2) } .property instance int32 P(int32, int32) { .get instance int32 A::get_P(int32, int32) .set instance void A::set_P(int32, int32, int32) } }"; var reference1 = CompileIL(source1); var source2 = @"using System; class B : A { public override int this[int x, int y = 3] { get { Console.WriteLine(""get_P: {0}"", y); return 0; } set { Console.WriteLine(""set_P: {0}"", y); } } } class C { static void Main() { B b = new B(); b[0] = b[0]; b[1] += 1; A a = b; a[0] = a[0]; a[1] += 1; // Dev11 uses get_P default for both } }"; var compilation2 = CompileAndVerify(source2, references: new[] { reference1 }, expectedOutput: @"get_P: 3 set_P: 3 get_P: 3 set_P: 3 get_P: 1 set_P: 2 get_P: 1 set_P: 1"); } [Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")] public void RetargetingIndexerMetadataName() { #region "Source" var src1 = @"using System; public interface IGoo { int this[int i] { get; } } public class Goo : IGoo { public int this[int i] { get { return i; } } } "; var src2 = @"using System; class Test { public void M() { IGoo igoo = new Goo(); var local = igoo[100]; } } "; #endregion var comp1 = CreateEmptyCompilation(src1, new[] { TestMetadata.Net40.mscorlib }); var comp2 = CreateCompilation(src2, new[] { new CSharpCompilationReference(comp1) }); var typeSymbol = comp1.SourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("IGoo"); var idxSymbol = typeSymbol.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.NotNull(idxSymbol); Assert.Equal("this[]", idxSymbol.Name); Assert.Equal("Item", idxSymbol.MetadataName); var tree = comp2.SyntaxTrees[0]; var model = comp2.GetSemanticModel(tree); ExpressionSyntax expr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().FirstOrDefault(); var idxSymbol2 = model.GetSymbolInfo(expr); Assert.NotNull(idxSymbol2.Symbol); Assert.Equal(WellKnownMemberNames.Indexer, idxSymbol2.Symbol.Name); Assert.Equal("Item", idxSymbol2.Symbol.MetadataName); } [Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")] public void SubstitutedIndexerMetadataName() { var source = @" class C<T> { int this[int x] { get { return 0; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var unsubstitutedType = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var unsubstitutedIndexer = unsubstitutedType.GetMember<SourcePropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal(WellKnownMemberNames.Indexer, unsubstitutedIndexer.Name); Assert.Equal("Item", unsubstitutedIndexer.MetadataName); var substitutedType = unsubstitutedType.Construct(comp.GetSpecialType(SpecialType.System_Int32)); var substitutedIndexer = substitutedType.GetMember<SubstitutedPropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal(WellKnownMemberNames.Indexer, substitutedIndexer.Name); Assert.Equal("Item", substitutedIndexer.MetadataName); } [Fact, WorkItem(806258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/806258")] public void ConflictWithTypeParameter() { var source = @" class C<Item, get_Item> { int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (4,9): error CS0102: The type 'C<Item, get_Item>' already contains a definition for 'Item' // int this[int x] { get { return 0; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("C<Item, get_Item>", "Item"), // (4,23): error CS0102: The type 'C<Item, get_Item>' already contains a definition for 'get_Item' // int this[int x] { get { return 0; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("C<Item, get_Item>", "get_Item")); } [Fact, WorkItem(806258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/806258")] public void ConflictWithTypeParameter_IndexerNameAttribute() { var source = @" using System.Runtime.CompilerServices; class C<A, get_A> { [IndexerName(""A"")] int this[int x] { get { return 0; } } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0102: The type 'C<A, get_A>' already contains a definition for 'A' // int this[int x] { get { return 0; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("C<A, get_A>", "A"), // (7,23): error CS0102: The type 'C<A, get_A>' already contains a definition for 'get_A' // int this[int x] { get { return 0; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("C<A, get_A>", "get_A")); } [Fact] public void IndexerNameNoConstantValue() { var source = @"using System.Runtime.CompilerServices; class C { const string F; [IndexerName(F)] object this[object o] { get { return null; } } }"; CreateCompilation(source).VerifyDiagnostics( // (4,18): error CS0145: A const field requires a value to be provided // const string F; Diagnostic(ErrorCode.ERR_ConstValueRequired, "F").WithLocation(4, 18), // (5,18): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [IndexerName(F)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F").WithLocation(5, 18)); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/VisualBasic/Portable/Structure/Providers/TypeDeclarationStructureProvider.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 TypeDeclarationStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of TypeStatementSyntax) Protected Overrides Sub CollectBlockSpans(typeDeclaration As TypeStatementSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) CollectCommentsRegions(typeDeclaration, spans, optionProvider) Dim block = TryCast(typeDeclaration.Parent, TypeBlockSyntax) If Not block?.EndBlockStatement.IsMissing Then spans.AddIfNotNull(CreateBlockSpanFromBlock( block, bannerNode:=typeDeclaration, autoCollapse:=False, type:=BlockTypes.Type, isCollapsible:=True)) CollectCommentsRegions(block.EndBlockStatement, spans, optionProvider) End If 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 TypeDeclarationStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of TypeStatementSyntax) Protected Overrides Sub CollectBlockSpans(typeDeclaration As TypeStatementSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) CollectCommentsRegions(typeDeclaration, spans, optionProvider) Dim block = TryCast(typeDeclaration.Parent, TypeBlockSyntax) If Not block?.EndBlockStatement.IsMissing Then spans.AddIfNotNull(CreateBlockSpanFromBlock( block, bannerNode:=typeDeclaration, autoCollapse:=False, type:=BlockTypes.Type, isCollapsible:=True)) CollectCommentsRegions(block.EndBlockStatement, spans, optionProvider) End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Core/Portable/CodeGen/VariableSlotAllocator.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.Reflection.Metadata; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CodeGen { internal abstract class VariableSlotAllocator { public abstract void AddPreviousLocals(ArrayBuilder<Cci.ILocalDefinition> builder); public abstract LocalDefinition? GetPreviousLocal( Cci.ITypeReference type, ILocalSymbolInternal symbol, string? name, SynthesizedLocalKind kind, LocalDebugId id, LocalVariableAttributes pdbAttributes, LocalSlotConstraints constraints, ImmutableArray<bool> dynamicTransformFlags, ImmutableArray<string> tupleElementNames); public abstract string? PreviousStateMachineTypeName { get; } /// <summary> /// Returns an index of a slot that stores specified hoisted local variable in the previous generation. /// </summary> public abstract bool TryGetPreviousHoistedLocalSlotIndex( SyntaxNode currentDeclarator, Cci.ITypeReference currentType, SynthesizedLocalKind synthesizedKind, LocalDebugId currentId, DiagnosticBag diagnostics, out int slotIndex); /// <summary> /// Number of slots reserved for hoisted local variables. /// </summary> /// <remarks> /// Some of the slots might not be used anymore (a variable might have been deleted or its type changed). /// Still, new hoisted variables are assigned slots starting with <see cref="PreviousHoistedLocalSlotCount"/>. /// </remarks> public abstract int PreviousHoistedLocalSlotCount { get; } /// <summary> /// Returns true and an index of a slot that stores an awaiter of a specified type in the previous generation, if any. /// </summary> public abstract bool TryGetPreviousAwaiterSlotIndex(Cci.ITypeReference currentType, DiagnosticBag diagnostics, out int slotIndex); /// <summary> /// Number of slots reserved for awaiters. /// </summary> /// <remarks> /// Some of the slots might not be used anymore (the type of an awaiter might have changed). /// Still, new awaiters are assigned slots starting with <see cref="PreviousAwaiterSlotCount"/>. /// </remarks> public abstract int PreviousAwaiterSlotCount { get; } /// <summary> /// The id of the method, or null if the method wasn't assigned one. /// </summary> public abstract DebugId? MethodId { get; } /// <summary> /// Finds a closure in the previous generation that corresponds to the specified syntax. /// </summary> /// <remarks> /// See LambdaFrame.AssertIsLambdaScopeSyntax for kinds of syntax nodes that represent closures. /// </remarks> public abstract bool TryGetPreviousClosure(SyntaxNode closureSyntax, out DebugId closureId); /// <summary> /// Finds a lambda in the previous generation that corresponds to the specified syntax. /// The <paramref name="lambdaOrLambdaBodySyntax"/> is either a lambda syntax (<paramref name="isLambdaBody"/> is false), /// or lambda body syntax (<paramref name="isLambdaBody"/> is true). /// </summary> public abstract bool TryGetPreviousLambda(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out DebugId lambdaId); } }
// 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.Reflection.Metadata; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CodeGen { internal abstract class VariableSlotAllocator { public abstract void AddPreviousLocals(ArrayBuilder<Cci.ILocalDefinition> builder); public abstract LocalDefinition? GetPreviousLocal( Cci.ITypeReference type, ILocalSymbolInternal symbol, string? name, SynthesizedLocalKind kind, LocalDebugId id, LocalVariableAttributes pdbAttributes, LocalSlotConstraints constraints, ImmutableArray<bool> dynamicTransformFlags, ImmutableArray<string> tupleElementNames); public abstract string? PreviousStateMachineTypeName { get; } /// <summary> /// Returns an index of a slot that stores specified hoisted local variable in the previous generation. /// </summary> public abstract bool TryGetPreviousHoistedLocalSlotIndex( SyntaxNode currentDeclarator, Cci.ITypeReference currentType, SynthesizedLocalKind synthesizedKind, LocalDebugId currentId, DiagnosticBag diagnostics, out int slotIndex); /// <summary> /// Number of slots reserved for hoisted local variables. /// </summary> /// <remarks> /// Some of the slots might not be used anymore (a variable might have been deleted or its type changed). /// Still, new hoisted variables are assigned slots starting with <see cref="PreviousHoistedLocalSlotCount"/>. /// </remarks> public abstract int PreviousHoistedLocalSlotCount { get; } /// <summary> /// Returns true and an index of a slot that stores an awaiter of a specified type in the previous generation, if any. /// </summary> public abstract bool TryGetPreviousAwaiterSlotIndex(Cci.ITypeReference currentType, DiagnosticBag diagnostics, out int slotIndex); /// <summary> /// Number of slots reserved for awaiters. /// </summary> /// <remarks> /// Some of the slots might not be used anymore (the type of an awaiter might have changed). /// Still, new awaiters are assigned slots starting with <see cref="PreviousAwaiterSlotCount"/>. /// </remarks> public abstract int PreviousAwaiterSlotCount { get; } /// <summary> /// The id of the method, or null if the method wasn't assigned one. /// </summary> public abstract DebugId? MethodId { get; } /// <summary> /// Finds a closure in the previous generation that corresponds to the specified syntax. /// </summary> /// <remarks> /// See LambdaFrame.AssertIsLambdaScopeSyntax for kinds of syntax nodes that represent closures. /// </remarks> public abstract bool TryGetPreviousClosure(SyntaxNode closureSyntax, out DebugId closureId); /// <summary> /// Finds a lambda in the previous generation that corresponds to the specified syntax. /// The <paramref name="lambdaOrLambdaBodySyntax"/> is either a lambda syntax (<paramref name="isLambdaBody"/> is false), /// or lambda body syntax (<paramref name="isLambdaBody"/> is true). /// </summary> public abstract bool TryGetPreviousLambda(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out DebugId lambdaId); } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxNodeCache.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 Microsoft.CodeAnalysis.Syntax.InternalSyntax; using System; using System.Diagnostics; using Roslyn.Utilities; #if STATS using System.Threading; #endif namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { /// <summary> /// Provides caching functionality for green nonterminals with up to 3 children. /// Example: /// When constructing a node with given kind, flags, child1 and child2, we can look up /// in the cache whether we already have a node that contains same kind, flags, /// child1 and child2 and use that. /// /// For the purpose of children comparison, reference equality is used as a much cheaper /// alternative to the structural/recursive equality. This implies that in order to de-duplicate /// a node to a cache node, the children of two nodes must be already de-duplicated. /// When adding a node to the cache we verify that cache does contain node's children, /// since otherwise there is no reason for the node to be used. /// Tokens/nulls are for this purpose considered deduplicated. Indeed most of the tokens /// are deduplicated via quick-scanner caching, so we just assume they all are. /// /// As a result of above, "fat" nodes with 4 or more children or their recursive parents /// will never be in the cache. This naturally limits the typical single cache item to be /// a relatively simple expression. We do not want the cache to be completely unbounded /// on the item size. /// While it still may be possible to store a gigantic nested binary expression, /// it should be a rare occurrence. /// /// We only consider "normal" nodes to be cacheable. /// Nodes with diagnostics/annotations/directives/skipped, etc... have more complicated identity /// and are not likely to be repetitive. /// /// </summary> internal class GreenStats { // TODO: remove when done tweaking this cache. #if STATS private static GreenStats stats = new GreenStats(); private int greenNodes; private int greenTokens; private int nontermsAdded; private int cacheableNodes; private int cacheHits; internal static void NoteGreen(GreenNode node) { Interlocked.Increment(ref stats.greenNodes); if (node.IsToken) { Interlocked.Increment(ref stats.greenTokens); } } internal static void ItemAdded() { Interlocked.Increment(ref stats.nontermsAdded); } internal static void ItemCacheable() { Interlocked.Increment(ref stats.cacheableNodes); } internal static void CacheHit() { Interlocked.Increment(ref stats.cacheHits); } ~GreenStats() { Console.WriteLine("Green: " + greenNodes); Console.WriteLine("GreenTk: " + greenTokens); Console.WriteLine("Nonterminals added: " + nontermsAdded); Console.WriteLine("Nonterminals cacheable: " + cacheableNodes); Console.WriteLine("CacheHits: " + cacheHits); Console.WriteLine("RateOfAll: " + (cacheHits * 100 / (cacheHits + greenNodes - greenTokens)) + "%"); Console.WriteLine("RateOfCacheable: " + (cacheHits * 100 / (cacheableNodes)) + "%"); } #else internal static void NoteGreen(GreenNode node) { } [Conditional("DEBUG")] internal static void ItemAdded() { } [Conditional("DEBUG")] internal static void ItemCacheable() { } [Conditional("DEBUG")] internal static void CacheHit() { } #endif } internal static class SyntaxNodeCache { private const int CacheSizeBits = 16; private const int CacheSize = 1 << CacheSizeBits; private const int CacheMask = CacheSize - 1; private readonly struct Entry { public readonly int hash; public readonly GreenNode? node; internal Entry(int hash, GreenNode node) { this.hash = hash; this.node = node; } } private static readonly Entry[] s_cache = new Entry[CacheSize]; internal static void AddNode(GreenNode node, int hash) { if (AllChildrenInCache(node) && !node.IsMissing) { GreenStats.ItemAdded(); Debug.Assert(node.GetCacheHash() == hash); var idx = hash & CacheMask; s_cache[idx] = new Entry(hash, node); } } private static bool CanBeCached(GreenNode? child1) { return child1 == null || child1.IsCacheable; } private static bool CanBeCached(GreenNode? child1, GreenNode? child2) { return CanBeCached(child1) && CanBeCached(child2); } private static bool CanBeCached(GreenNode? child1, GreenNode? child2, GreenNode? child3) { return CanBeCached(child1) && CanBeCached(child2) && CanBeCached(child3); } private static bool ChildInCache(GreenNode? child) { // for the purpose of this function consider that // null nodes, tokens and trivias are cached somewhere else. // TODO: should use slotCount if (child == null || child.SlotCount == 0) return true; int hash = child.GetCacheHash(); int idx = hash & CacheMask; return s_cache[idx].node == child; } private static bool AllChildrenInCache(GreenNode node) { // TODO: should use slotCount var cnt = node.SlotCount; for (int i = 0; i < cnt; i++) { if (!ChildInCache(node.GetSlot(i))) { return false; } } return true; } internal static GreenNode? TryGetNode(int kind, GreenNode? child1, out int hash) { return TryGetNode(kind, child1, GetDefaultNodeFlags(), out hash); } internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode.NodeFlags flags, out int hash) { if (CanBeCached(child1)) { GreenStats.ItemCacheable(); int h = hash = GetCacheHash(kind, flags, child1); int idx = h & CacheMask; var e = s_cache[idx]; if (e.hash == h && e.node != null && e.node.IsCacheEquivalent(kind, flags, child1)) { GreenStats.CacheHit(); return e.node; } } else { hash = -1; } return null; } internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, out int hash) { return TryGetNode(kind, child1, child2, GetDefaultNodeFlags(), out hash); } internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, GreenNode.NodeFlags flags, out int hash) { if (CanBeCached(child1, child2)) { GreenStats.ItemCacheable(); int h = hash = GetCacheHash(kind, flags, child1, child2); int idx = h & CacheMask; var e = s_cache[idx]; if (e.hash == h && e.node != null && e.node.IsCacheEquivalent(kind, flags, child1, child2)) { GreenStats.CacheHit(); return e.node; } } else { hash = -1; } return null; } internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, GreenNode? child3, out int hash) { return TryGetNode(kind, child1, child2, child3, GetDefaultNodeFlags(), out hash); } internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, GreenNode? child3, GreenNode.NodeFlags flags, out int hash) { if (CanBeCached(child1, child2, child3)) { GreenStats.ItemCacheable(); int h = hash = GetCacheHash(kind, flags, child1, child2, child3); int idx = h & CacheMask; var e = s_cache[idx]; if (e.hash == h && e.node != null && e.node.IsCacheEquivalent(kind, flags, child1, child2, child3)) { GreenStats.CacheHit(); return e.node; } } else { hash = -1; } return null; } public static GreenNode.NodeFlags GetDefaultNodeFlags() { return GreenNode.NodeFlags.IsNotMissing; } private static int GetCacheHash(int kind, GreenNode.NodeFlags flags, GreenNode? child1) { int code = (int)(flags) ^ kind; // the only child is never null // https://github.com/dotnet/roslyn/issues/41539 code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child1!), code); // ensure nonnegative hash return code & Int32.MaxValue; } private static int GetCacheHash(int kind, GreenNode.NodeFlags flags, GreenNode? child1, GreenNode? child2) { int code = (int)(flags) ^ kind; if (child1 != null) { code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child1), code); } if (child2 != null) { code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child2), code); } // ensure nonnegative hash return code & Int32.MaxValue; } private static int GetCacheHash(int kind, GreenNode.NodeFlags flags, GreenNode? child1, GreenNode? child2, GreenNode? child3) { int code = (int)(flags) ^ kind; if (child1 != null) { code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child1), code); } if (child2 != null) { code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child2), code); } if (child3 != null) { code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child3), code); } // ensure nonnegative hash return code & Int32.MaxValue; } } }
// 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 Microsoft.CodeAnalysis.Syntax.InternalSyntax; using System; using System.Diagnostics; using Roslyn.Utilities; #if STATS using System.Threading; #endif namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { /// <summary> /// Provides caching functionality for green nonterminals with up to 3 children. /// Example: /// When constructing a node with given kind, flags, child1 and child2, we can look up /// in the cache whether we already have a node that contains same kind, flags, /// child1 and child2 and use that. /// /// For the purpose of children comparison, reference equality is used as a much cheaper /// alternative to the structural/recursive equality. This implies that in order to de-duplicate /// a node to a cache node, the children of two nodes must be already de-duplicated. /// When adding a node to the cache we verify that cache does contain node's children, /// since otherwise there is no reason for the node to be used. /// Tokens/nulls are for this purpose considered deduplicated. Indeed most of the tokens /// are deduplicated via quick-scanner caching, so we just assume they all are. /// /// As a result of above, "fat" nodes with 4 or more children or their recursive parents /// will never be in the cache. This naturally limits the typical single cache item to be /// a relatively simple expression. We do not want the cache to be completely unbounded /// on the item size. /// While it still may be possible to store a gigantic nested binary expression, /// it should be a rare occurrence. /// /// We only consider "normal" nodes to be cacheable. /// Nodes with diagnostics/annotations/directives/skipped, etc... have more complicated identity /// and are not likely to be repetitive. /// /// </summary> internal class GreenStats { // TODO: remove when done tweaking this cache. #if STATS private static GreenStats stats = new GreenStats(); private int greenNodes; private int greenTokens; private int nontermsAdded; private int cacheableNodes; private int cacheHits; internal static void NoteGreen(GreenNode node) { Interlocked.Increment(ref stats.greenNodes); if (node.IsToken) { Interlocked.Increment(ref stats.greenTokens); } } internal static void ItemAdded() { Interlocked.Increment(ref stats.nontermsAdded); } internal static void ItemCacheable() { Interlocked.Increment(ref stats.cacheableNodes); } internal static void CacheHit() { Interlocked.Increment(ref stats.cacheHits); } ~GreenStats() { Console.WriteLine("Green: " + greenNodes); Console.WriteLine("GreenTk: " + greenTokens); Console.WriteLine("Nonterminals added: " + nontermsAdded); Console.WriteLine("Nonterminals cacheable: " + cacheableNodes); Console.WriteLine("CacheHits: " + cacheHits); Console.WriteLine("RateOfAll: " + (cacheHits * 100 / (cacheHits + greenNodes - greenTokens)) + "%"); Console.WriteLine("RateOfCacheable: " + (cacheHits * 100 / (cacheableNodes)) + "%"); } #else internal static void NoteGreen(GreenNode node) { } [Conditional("DEBUG")] internal static void ItemAdded() { } [Conditional("DEBUG")] internal static void ItemCacheable() { } [Conditional("DEBUG")] internal static void CacheHit() { } #endif } internal static class SyntaxNodeCache { private const int CacheSizeBits = 16; private const int CacheSize = 1 << CacheSizeBits; private const int CacheMask = CacheSize - 1; private readonly struct Entry { public readonly int hash; public readonly GreenNode? node; internal Entry(int hash, GreenNode node) { this.hash = hash; this.node = node; } } private static readonly Entry[] s_cache = new Entry[CacheSize]; internal static void AddNode(GreenNode node, int hash) { if (AllChildrenInCache(node) && !node.IsMissing) { GreenStats.ItemAdded(); Debug.Assert(node.GetCacheHash() == hash); var idx = hash & CacheMask; s_cache[idx] = new Entry(hash, node); } } private static bool CanBeCached(GreenNode? child1) { return child1 == null || child1.IsCacheable; } private static bool CanBeCached(GreenNode? child1, GreenNode? child2) { return CanBeCached(child1) && CanBeCached(child2); } private static bool CanBeCached(GreenNode? child1, GreenNode? child2, GreenNode? child3) { return CanBeCached(child1) && CanBeCached(child2) && CanBeCached(child3); } private static bool ChildInCache(GreenNode? child) { // for the purpose of this function consider that // null nodes, tokens and trivias are cached somewhere else. // TODO: should use slotCount if (child == null || child.SlotCount == 0) return true; int hash = child.GetCacheHash(); int idx = hash & CacheMask; return s_cache[idx].node == child; } private static bool AllChildrenInCache(GreenNode node) { // TODO: should use slotCount var cnt = node.SlotCount; for (int i = 0; i < cnt; i++) { if (!ChildInCache(node.GetSlot(i))) { return false; } } return true; } internal static GreenNode? TryGetNode(int kind, GreenNode? child1, out int hash) { return TryGetNode(kind, child1, GetDefaultNodeFlags(), out hash); } internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode.NodeFlags flags, out int hash) { if (CanBeCached(child1)) { GreenStats.ItemCacheable(); int h = hash = GetCacheHash(kind, flags, child1); int idx = h & CacheMask; var e = s_cache[idx]; if (e.hash == h && e.node != null && e.node.IsCacheEquivalent(kind, flags, child1)) { GreenStats.CacheHit(); return e.node; } } else { hash = -1; } return null; } internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, out int hash) { return TryGetNode(kind, child1, child2, GetDefaultNodeFlags(), out hash); } internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, GreenNode.NodeFlags flags, out int hash) { if (CanBeCached(child1, child2)) { GreenStats.ItemCacheable(); int h = hash = GetCacheHash(kind, flags, child1, child2); int idx = h & CacheMask; var e = s_cache[idx]; if (e.hash == h && e.node != null && e.node.IsCacheEquivalent(kind, flags, child1, child2)) { GreenStats.CacheHit(); return e.node; } } else { hash = -1; } return null; } internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, GreenNode? child3, out int hash) { return TryGetNode(kind, child1, child2, child3, GetDefaultNodeFlags(), out hash); } internal static GreenNode? TryGetNode(int kind, GreenNode? child1, GreenNode? child2, GreenNode? child3, GreenNode.NodeFlags flags, out int hash) { if (CanBeCached(child1, child2, child3)) { GreenStats.ItemCacheable(); int h = hash = GetCacheHash(kind, flags, child1, child2, child3); int idx = h & CacheMask; var e = s_cache[idx]; if (e.hash == h && e.node != null && e.node.IsCacheEquivalent(kind, flags, child1, child2, child3)) { GreenStats.CacheHit(); return e.node; } } else { hash = -1; } return null; } public static GreenNode.NodeFlags GetDefaultNodeFlags() { return GreenNode.NodeFlags.IsNotMissing; } private static int GetCacheHash(int kind, GreenNode.NodeFlags flags, GreenNode? child1) { int code = (int)(flags) ^ kind; // the only child is never null // https://github.com/dotnet/roslyn/issues/41539 code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child1!), code); // ensure nonnegative hash return code & Int32.MaxValue; } private static int GetCacheHash(int kind, GreenNode.NodeFlags flags, GreenNode? child1, GreenNode? child2) { int code = (int)(flags) ^ kind; if (child1 != null) { code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child1), code); } if (child2 != null) { code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child2), code); } // ensure nonnegative hash return code & Int32.MaxValue; } private static int GetCacheHash(int kind, GreenNode.NodeFlags flags, GreenNode? child1, GreenNode? child2, GreenNode? child3) { int code = (int)(flags) ^ kind; if (child1 != null) { code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child1), code); } if (child2 != null) { code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child2), code); } if (child3 != null) { code = Hash.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(child3), code); } // ensure nonnegative hash return code & Int32.MaxValue; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/CSharp/Portable/Symbols/Source/CustomModifierUtils.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.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.PooledObjects; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class CustomModifierUtils { /// <remarks> /// Out params are updated by assignment. If you require thread-safety, pass temps and then /// CompareExchange them back into shared memory. /// </remarks> internal static void CopyMethodCustomModifiers( MethodSymbol sourceMethod, MethodSymbol destinationMethod, out TypeWithAnnotations returnType, out ImmutableArray<CustomModifier> customModifiers, out ImmutableArray<ParameterSymbol> parameters, bool alsoCopyParamsModifier) // Last since always named. { Debug.Assert((object)sourceMethod != null); // Assert: none of the method's type parameters have been substituted Debug.Assert((object)sourceMethod == sourceMethod.ConstructedFrom); // For the most part, we will copy custom modifiers by copying types. // The only time when this fails is when the type refers to a type parameter // owned by the overridden method. We need to replace all such references // with (equivalent) type parameters owned by this method. We know that // we can perform this mapping positionally, because the method signatures // have already been compared. MethodSymbol constructedSourceMethod = sourceMethod.ConstructIfGeneric(destinationMethod.TypeArgumentsWithAnnotations); customModifiers = destinationMethod.RefKind != RefKind.None ? constructedSourceMethod.RefCustomModifiers : ImmutableArray<CustomModifier>.Empty; parameters = CopyParameterCustomModifiers(constructedSourceMethod.Parameters, destinationMethod.Parameters, alsoCopyParamsModifier); returnType = destinationMethod.ReturnTypeWithAnnotations; // Default value - in case we don't copy the custom modifiers. TypeSymbol returnTypeSymbol = returnType.Type; var sourceMethodReturnType = constructedSourceMethod.ReturnTypeWithAnnotations; // We do an extra check before copying the return type to handle the case where the overriding // method (incorrectly) has a different return type than the overridden method. In such cases, // we want to retain the original (incorrect) return type to avoid hiding the return type // given in source. TypeSymbol returnTypeWithCustomModifiers = sourceMethodReturnType.Type; if (returnTypeSymbol.Equals(returnTypeWithCustomModifiers, TypeCompareKind.AllIgnoreOptions)) { returnType = returnType.WithTypeAndModifiers(CopyTypeCustomModifiers(returnTypeWithCustomModifiers, returnTypeSymbol, destinationMethod.ContainingAssembly), sourceMethodReturnType.CustomModifiers); } } /// <param name="sourceType">Type that already has custom modifiers.</param> /// <param name="destinationType">Same as <paramref name="sourceType"/>, but without custom modifiers. /// May differ in object/dynamic, tuple element names, or other differences ignored by the runtime.</param> /// <param name="containingAssembly">The assembly containing the signature referring to the destination type.</param> /// <returns><paramref name="destinationType"/> with custom modifiers copied from <paramref name="sourceType"/>.</returns> internal static TypeSymbol CopyTypeCustomModifiers(TypeSymbol sourceType, TypeSymbol destinationType, AssemblySymbol containingAssembly) { Debug.Assert(sourceType.Equals(destinationType, TypeCompareKind.AllIgnoreOptions)); const RefKind refKind = RefKind.None; // NOTE: overrides can differ by object/dynamic, tuple element names, etc. // If they do, we'll need to tweak destinationType before we can use it in place of sourceType. // NOTE: refKind is irrelevant here since we are just encoding/decoding the type. ImmutableArray<bool> flags = CSharpCompilation.DynamicTransformsEncoder.EncodeWithoutCustomModifierFlags(destinationType, refKind); TypeSymbol resultType = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(sourceType, containingAssembly, refKind, flags); var builder = ArrayBuilder<bool>.GetInstance(); CSharpCompilation.NativeIntegerTransformsEncoder.Encode(builder, destinationType); resultType = NativeIntegerTypeDecoder.TransformType(resultType, builder.ToImmutableAndFree()); if (destinationType.ContainsTuple() && !sourceType.Equals(destinationType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamic)) { // We also preserve tuple names, if present and different ImmutableArray<string> names = CSharpCompilation.TupleNamesEncoder.Encode(destinationType); resultType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(resultType, names); } // Preserve nullable modifiers as well. // https://github.com/dotnet/roslyn/issues/30077: Is it reasonable to copy annotations from the source? // If the destination had some of those annotations but not all, then clearly the destination // was incorrect. Or if the destination is C#7, then the destination will advertise annotations // that the author did not write and did not validate. var flagsBuilder = ArrayBuilder<byte>.GetInstance(); destinationType.AddNullableTransforms(flagsBuilder); int position = 0; int length = flagsBuilder.Count; bool transformResult = resultType.ApplyNullableTransforms(defaultTransformFlag: 0, flagsBuilder.ToImmutableAndFree(), ref position, out resultType); Debug.Assert(transformResult && position == length); Debug.Assert(resultType.Equals(sourceType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreNativeIntegers)); // Same custom modifiers as source type. // Same object/dynamic, nullability, native integers, and tuple names as destination type. Debug.Assert(resultType.Equals(destinationType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)); return resultType; } internal static ImmutableArray<ParameterSymbol> CopyParameterCustomModifiers(ImmutableArray<ParameterSymbol> sourceParameters, ImmutableArray<ParameterSymbol> destinationParameters, bool alsoCopyParamsModifier) { Debug.Assert(!destinationParameters.IsDefault); Debug.Assert(destinationParameters.All(p => p is SourceParameterSymbolBase)); Debug.Assert(sourceParameters.Length == destinationParameters.Length); // Nearly all of the time, there will be no custom modifiers to copy, so don't // allocate the builder until we know that we need it. ArrayBuilder<ParameterSymbol> builder = null; int numParams = destinationParameters.Length; for (int i = 0; i < numParams; i++) { SourceParameterSymbolBase destinationParameter = (SourceParameterSymbolBase)destinationParameters[i]; ParameterSymbol sourceParameter = sourceParameters[i]; if (sourceParameter.TypeWithAnnotations.CustomModifiers.Any() || sourceParameter.RefCustomModifiers.Any() || sourceParameter.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: true) || destinationParameter.TypeWithAnnotations.CustomModifiers.Any() || destinationParameter.RefCustomModifiers.Any() || destinationParameter.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: true) || // Could happen if the associated property has custom modifiers. (alsoCopyParamsModifier && (sourceParameter.IsParams != destinationParameter.IsParams))) { if (builder == null) { builder = ArrayBuilder<ParameterSymbol>.GetInstance(); builder.AddRange(destinationParameters, i); //add up to, but not including, the current parameter } bool newParams = alsoCopyParamsModifier ? sourceParameter.IsParams : destinationParameter.IsParams; builder.Add(destinationParameter.WithCustomModifiersAndParams(sourceParameter.Type, sourceParameter.TypeWithAnnotations.CustomModifiers, destinationParameter.RefKind != RefKind.None ? sourceParameter.RefCustomModifiers : ImmutableArray<CustomModifier>.Empty, newParams)); } else if (builder != null) { builder.Add(destinationParameter); } } return builder == null ? destinationParameters : builder.ToImmutableAndFree(); } internal static bool HasInAttributeModifier(this ImmutableArray<CustomModifier> modifiers) { return modifiers.Any(modifier => !modifier.IsOptional && ((CSharpCustomModifier)modifier).ModifierSymbol.IsWellKnownTypeInAttribute()); } internal static bool HasIsExternalInitModifier(this ImmutableArray<CustomModifier> modifiers) { return modifiers.Any(modifier => !modifier.IsOptional && ((CSharpCustomModifier)modifier).ModifierSymbol.IsWellKnownTypeIsExternalInit()); } internal static bool HasOutAttributeModifier(this ImmutableArray<CustomModifier> modifiers) { return modifiers.Any(modifier => !modifier.IsOptional && ((CSharpCustomModifier)modifier).ModifierSymbol.IsWellKnownTypeOutAttribute()); } } }
// 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.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.PooledObjects; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class CustomModifierUtils { /// <remarks> /// Out params are updated by assignment. If you require thread-safety, pass temps and then /// CompareExchange them back into shared memory. /// </remarks> internal static void CopyMethodCustomModifiers( MethodSymbol sourceMethod, MethodSymbol destinationMethod, out TypeWithAnnotations returnType, out ImmutableArray<CustomModifier> customModifiers, out ImmutableArray<ParameterSymbol> parameters, bool alsoCopyParamsModifier) // Last since always named. { Debug.Assert((object)sourceMethod != null); // Assert: none of the method's type parameters have been substituted Debug.Assert((object)sourceMethod == sourceMethod.ConstructedFrom); // For the most part, we will copy custom modifiers by copying types. // The only time when this fails is when the type refers to a type parameter // owned by the overridden method. We need to replace all such references // with (equivalent) type parameters owned by this method. We know that // we can perform this mapping positionally, because the method signatures // have already been compared. MethodSymbol constructedSourceMethod = sourceMethod.ConstructIfGeneric(destinationMethod.TypeArgumentsWithAnnotations); customModifiers = destinationMethod.RefKind != RefKind.None ? constructedSourceMethod.RefCustomModifiers : ImmutableArray<CustomModifier>.Empty; parameters = CopyParameterCustomModifiers(constructedSourceMethod.Parameters, destinationMethod.Parameters, alsoCopyParamsModifier); returnType = destinationMethod.ReturnTypeWithAnnotations; // Default value - in case we don't copy the custom modifiers. TypeSymbol returnTypeSymbol = returnType.Type; var sourceMethodReturnType = constructedSourceMethod.ReturnTypeWithAnnotations; // We do an extra check before copying the return type to handle the case where the overriding // method (incorrectly) has a different return type than the overridden method. In such cases, // we want to retain the original (incorrect) return type to avoid hiding the return type // given in source. TypeSymbol returnTypeWithCustomModifiers = sourceMethodReturnType.Type; if (returnTypeSymbol.Equals(returnTypeWithCustomModifiers, TypeCompareKind.AllIgnoreOptions)) { returnType = returnType.WithTypeAndModifiers(CopyTypeCustomModifiers(returnTypeWithCustomModifiers, returnTypeSymbol, destinationMethod.ContainingAssembly), sourceMethodReturnType.CustomModifiers); } } /// <param name="sourceType">Type that already has custom modifiers.</param> /// <param name="destinationType">Same as <paramref name="sourceType"/>, but without custom modifiers. /// May differ in object/dynamic, tuple element names, or other differences ignored by the runtime.</param> /// <param name="containingAssembly">The assembly containing the signature referring to the destination type.</param> /// <returns><paramref name="destinationType"/> with custom modifiers copied from <paramref name="sourceType"/>.</returns> internal static TypeSymbol CopyTypeCustomModifiers(TypeSymbol sourceType, TypeSymbol destinationType, AssemblySymbol containingAssembly) { Debug.Assert(sourceType.Equals(destinationType, TypeCompareKind.AllIgnoreOptions)); const RefKind refKind = RefKind.None; // NOTE: overrides can differ by object/dynamic, tuple element names, etc. // If they do, we'll need to tweak destinationType before we can use it in place of sourceType. // NOTE: refKind is irrelevant here since we are just encoding/decoding the type. ImmutableArray<bool> flags = CSharpCompilation.DynamicTransformsEncoder.EncodeWithoutCustomModifierFlags(destinationType, refKind); TypeSymbol resultType = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(sourceType, containingAssembly, refKind, flags); var builder = ArrayBuilder<bool>.GetInstance(); CSharpCompilation.NativeIntegerTransformsEncoder.Encode(builder, destinationType); resultType = NativeIntegerTypeDecoder.TransformType(resultType, builder.ToImmutableAndFree()); if (destinationType.ContainsTuple() && !sourceType.Equals(destinationType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamic)) { // We also preserve tuple names, if present and different ImmutableArray<string> names = CSharpCompilation.TupleNamesEncoder.Encode(destinationType); resultType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(resultType, names); } // Preserve nullable modifiers as well. // https://github.com/dotnet/roslyn/issues/30077: Is it reasonable to copy annotations from the source? // If the destination had some of those annotations but not all, then clearly the destination // was incorrect. Or if the destination is C#7, then the destination will advertise annotations // that the author did not write and did not validate. var flagsBuilder = ArrayBuilder<byte>.GetInstance(); destinationType.AddNullableTransforms(flagsBuilder); int position = 0; int length = flagsBuilder.Count; bool transformResult = resultType.ApplyNullableTransforms(defaultTransformFlag: 0, flagsBuilder.ToImmutableAndFree(), ref position, out resultType); Debug.Assert(transformResult && position == length); Debug.Assert(resultType.Equals(sourceType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreNativeIntegers)); // Same custom modifiers as source type. // Same object/dynamic, nullability, native integers, and tuple names as destination type. Debug.Assert(resultType.Equals(destinationType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)); return resultType; } internal static ImmutableArray<ParameterSymbol> CopyParameterCustomModifiers(ImmutableArray<ParameterSymbol> sourceParameters, ImmutableArray<ParameterSymbol> destinationParameters, bool alsoCopyParamsModifier) { Debug.Assert(!destinationParameters.IsDefault); Debug.Assert(destinationParameters.All(p => p is SourceParameterSymbolBase)); Debug.Assert(sourceParameters.Length == destinationParameters.Length); // Nearly all of the time, there will be no custom modifiers to copy, so don't // allocate the builder until we know that we need it. ArrayBuilder<ParameterSymbol> builder = null; int numParams = destinationParameters.Length; for (int i = 0; i < numParams; i++) { SourceParameterSymbolBase destinationParameter = (SourceParameterSymbolBase)destinationParameters[i]; ParameterSymbol sourceParameter = sourceParameters[i]; if (sourceParameter.TypeWithAnnotations.CustomModifiers.Any() || sourceParameter.RefCustomModifiers.Any() || sourceParameter.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: true) || destinationParameter.TypeWithAnnotations.CustomModifiers.Any() || destinationParameter.RefCustomModifiers.Any() || destinationParameter.Type.HasCustomModifiers(flagNonDefaultArraySizesOrLowerBounds: true) || // Could happen if the associated property has custom modifiers. (alsoCopyParamsModifier && (sourceParameter.IsParams != destinationParameter.IsParams))) { if (builder == null) { builder = ArrayBuilder<ParameterSymbol>.GetInstance(); builder.AddRange(destinationParameters, i); //add up to, but not including, the current parameter } bool newParams = alsoCopyParamsModifier ? sourceParameter.IsParams : destinationParameter.IsParams; builder.Add(destinationParameter.WithCustomModifiersAndParams(sourceParameter.Type, sourceParameter.TypeWithAnnotations.CustomModifiers, destinationParameter.RefKind != RefKind.None ? sourceParameter.RefCustomModifiers : ImmutableArray<CustomModifier>.Empty, newParams)); } else if (builder != null) { builder.Add(destinationParameter); } } return builder == null ? destinationParameters : builder.ToImmutableAndFree(); } internal static bool HasInAttributeModifier(this ImmutableArray<CustomModifier> modifiers) { return modifiers.Any(modifier => !modifier.IsOptional && ((CSharpCustomModifier)modifier).ModifierSymbol.IsWellKnownTypeInAttribute()); } internal static bool HasIsExternalInitModifier(this ImmutableArray<CustomModifier> modifiers) { return modifiers.Any(modifier => !modifier.IsOptional && ((CSharpCustomModifier)modifier).ModifierSymbol.IsWellKnownTypeIsExternalInit()); } internal static bool HasOutAttributeModifier(this ImmutableArray<CustomModifier> modifiers) { return modifiers.Any(modifier => !modifier.IsOptional && ((CSharpCustomModifier)modifier).ModifierSymbol.IsWellKnownTypeOutAttribute()); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/GenericConstraintsKeywordRecommender.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.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations Friend Class GenericConstraintsKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken Dim recommendations As New List(Of RecommendedKeyword) recommendations.Add(New RecommendedKeyword("Class", VBFeaturesResources.Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_reference_type)) recommendations.Add(New RecommendedKeyword("Structure", VBFeaturesResources.Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_value_type)) recommendations.Add(New RecommendedKeyword("New", VBFeaturesResources.Specifies_a_constructor_constraint_on_a_generic_type_parameter)) If targetToken.IsChildToken(Of TypeParameterSingleConstraintClauseSyntax)(Function(constraint) constraint.AsKeyword) Then Return recommendations.ToImmutableArray() ElseIf TypeOf targetToken.Parent Is TypeParameterMultipleConstraintClauseSyntax Then Dim multipleConstraint = DirectCast(targetToken.Parent, TypeParameterMultipleConstraintClauseSyntax) If targetToken = multipleConstraint.OpenBraceToken OrElse targetToken.Kind = SyntaxKind.CommaToken Then Dim previousConstraints = multipleConstraint.Constraints.Where(Function(c) c.Span.End < context.Position).ToList() ' Structure can only be listed with previous type constraints If previousConstraints.Any(Function(constraint) Not constraint.IsKind(SyntaxKind.TypeConstraint)) Then recommendations.RemoveAll(Function(k) k.Keyword = "Structure") End If If previousConstraints.Any(Function(constraint) constraint.IsKind(SyntaxKind.ClassConstraint, SyntaxKind.StructureConstraint)) Then recommendations.RemoveAll(Function(k) k.Keyword = "Class") End If If previousConstraints.Any(Function(constraint) constraint.IsKind(SyntaxKind.NewConstraint, SyntaxKind.StructureConstraint)) Then recommendations.RemoveAll(Function(k) k.Keyword = "New") End If Return recommendations.ToImmutableArray() End If End If Return ImmutableArray(Of RecommendedKeyword).Empty 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.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations Friend Class GenericConstraintsKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken Dim recommendations As New List(Of RecommendedKeyword) recommendations.Add(New RecommendedKeyword("Class", VBFeaturesResources.Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_reference_type)) recommendations.Add(New RecommendedKeyword("Structure", VBFeaturesResources.Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_value_type)) recommendations.Add(New RecommendedKeyword("New", VBFeaturesResources.Specifies_a_constructor_constraint_on_a_generic_type_parameter)) If targetToken.IsChildToken(Of TypeParameterSingleConstraintClauseSyntax)(Function(constraint) constraint.AsKeyword) Then Return recommendations.ToImmutableArray() ElseIf TypeOf targetToken.Parent Is TypeParameterMultipleConstraintClauseSyntax Then Dim multipleConstraint = DirectCast(targetToken.Parent, TypeParameterMultipleConstraintClauseSyntax) If targetToken = multipleConstraint.OpenBraceToken OrElse targetToken.Kind = SyntaxKind.CommaToken Then Dim previousConstraints = multipleConstraint.Constraints.Where(Function(c) c.Span.End < context.Position).ToList() ' Structure can only be listed with previous type constraints If previousConstraints.Any(Function(constraint) Not constraint.IsKind(SyntaxKind.TypeConstraint)) Then recommendations.RemoveAll(Function(k) k.Keyword = "Structure") End If If previousConstraints.Any(Function(constraint) constraint.IsKind(SyntaxKind.ClassConstraint, SyntaxKind.StructureConstraint)) Then recommendations.RemoveAll(Function(k) k.Keyword = "Class") End If If previousConstraints.Any(Function(constraint) constraint.IsKind(SyntaxKind.NewConstraint, SyntaxKind.StructureConstraint)) Then recommendations.RemoveAll(Function(k) k.Keyword = "New") End If Return recommendations.ToImmutableArray() End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/VisualStudio/Core/Test/CodeModel/CSharp/CodeStructTests.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 Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeStructTests Inherits AbstractCodeStructTests #Region "Attributes tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes1() Dim code = <Code> struct $$C { } </Code> TestAttributes(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes2() Dim code = <Code> using System; [Serializable] struct $$C { } </Code> TestAttributes(code, IsElement("Serializable")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes3() Dim code = <Code>using System; [Serializable] [CLSCompliant(true)] struct $$C { } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes4() Dim code = <Code>using System; [Serializable, CLSCompliant(true)] struct $$C { } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub #End Region #Region "Bases tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBase1() Dim code = <Code> struct $$S { } </Code> TestBases(code, IsElement("ValueType", kind:=EnvDTE.vsCMElement.vsCMElementClass)) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBase2() Dim code = <Code> struct $$S : System.IDisposable { } </Code> TestBases(code, IsElement("ValueType", kind:=EnvDTE.vsCMElement.vsCMElementClass)) End Sub #End Region #Region "DataTypeKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDataTypeKind1() Dim code = <Code> struct $$S { } </Code> TestDataTypeKind(code, EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDataTypeKind2() Dim code = <Code> partial struct $$S { } partial struct S { } </Code> TestDataTypeKind(code, EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial) End Sub #End Region #Region "FullName tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName1() Dim code = <Code> struct $$S { } </Code> TestFullName(code, "S") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName2() Dim code = <Code> namespace N { struct $$S { } } </Code> TestFullName(code, "N.S") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName3() Dim code = <Code> namespace N { class C { struct $$S { } } } </Code> TestFullName(code, "N.C.S") End Sub #End Region #Region "ImplementedInterfaces tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestImplementedInterfaces1() Dim code = <Code> struct $$S : System.IDisposable { } </Code> TestImplementedInterfaces(code, IsElement("IDisposable", kind:=EnvDTE.vsCMElement.vsCMElementInterface)) End Sub #End Region #Region "Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName1() Dim code = <Code> struct $$S { } </Code> TestName(code, "S") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName2() Dim code = <Code> namespace N { struct $$S { } } </Code> TestName(code, "S") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName3() Dim code = <Code> namespace N { class C { struct $$S { } } } </Code> TestName(code, "S") End Sub #End Region #Region "Parent tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParent1() Dim code = <Code> struct $$S { } </Code> TestParent(code, IsFileCodeModel) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParent2() Dim code = <Code> namespace N { struct $$S { } } </Code> TestParent(code, IsElement("N", kind:=EnvDTE.vsCMElement.vsCMElementNamespace)) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParent3() Dim code = <Code> namespace N { class C { struct $$S { } } } </Code> TestParent(code, IsElement("C", kind:=EnvDTE.vsCMElement.vsCMElementClass)) End Sub #End Region #Region "Parts tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts1() Dim code = <Code> struct $$S { } </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts2() Dim code = <Code> partial struct $$S { } </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts3() Dim code = <Code> partial struct $$S { } partial struct S { } </Code> TestParts(code, 2) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> using System; struct $$S { } </Code> Dim expected = <Code> using System; [Serializable()] struct S { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> using System; [Serializable] struct $$S { } </Code> Dim expected = <Code> using System; [Serializable] [CLSCompliant(true)] struct S { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; struct $$S { } </Code> Dim expected = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] struct S { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function #End Region #Region "AddFunction tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction1() As Task Dim code = <Code> struct $$S { } </Code> Dim expected = <Code> struct S { void Goo() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void"}) End Function #End Region #Region "AddImplementedInterface tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAddImplementedInterface1() Dim code = <Code> struct $$S { } </Code> TestAddImplementedInterfaceThrows(Of ArgumentException)(code, "I", Nothing) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface2() As Task Dim code = <Code> struct $$S { } interface I { } </Code> Dim expected = <Code> struct S : I { } interface I { } </Code> Await TestAddImplementedInterface(code, "I", -1, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface3() As Task Dim code = <Code> struct $$S : I { } interface I { } interface J { } </Code> Dim expected = <Code> struct S : I, J { } interface I { } interface J { } </Code> Await TestAddImplementedInterface(code, "J", -1, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface4() As Task Dim code = <Code> struct $$S : I { } interface I { } interface J { } </Code> Dim expected = <Code> struct S : J, I { } interface I { } interface J { } </Code> Await TestAddImplementedInterface(code, "J", 0, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface5() As Task Dim code = <Code> struct $$S : I, K { } interface I { } interface J { } interface K { } </Code> Dim expected = <Code> struct S : I, J, K { } interface I { } interface J { } interface K { } </Code> Await TestAddImplementedInterface(code, "J", 1, expected) End Function #End Region #Region "RemoveImplementedInterface tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface1() As Task Dim code = <Code> struct $$S : I { } interface I { } </Code> Dim expected = <Code> struct S { } interface I { } </Code> Await TestRemoveImplementedInterface(code, "I", expected) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> struct $$Goo { } </Code> Dim expected = <Code> struct Bar { } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> struct $$S { } </Code> TestPropertyDescriptors(Of EnvDTE80.CodeStruct2)(code) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property 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 Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeStructTests Inherits AbstractCodeStructTests #Region "Attributes tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes1() Dim code = <Code> struct $$C { } </Code> TestAttributes(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes2() Dim code = <Code> using System; [Serializable] struct $$C { } </Code> TestAttributes(code, IsElement("Serializable")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes3() Dim code = <Code>using System; [Serializable] [CLSCompliant(true)] struct $$C { } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes4() Dim code = <Code>using System; [Serializable, CLSCompliant(true)] struct $$C { } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub #End Region #Region "Bases tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBase1() Dim code = <Code> struct $$S { } </Code> TestBases(code, IsElement("ValueType", kind:=EnvDTE.vsCMElement.vsCMElementClass)) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestBase2() Dim code = <Code> struct $$S : System.IDisposable { } </Code> TestBases(code, IsElement("ValueType", kind:=EnvDTE.vsCMElement.vsCMElementClass)) End Sub #End Region #Region "DataTypeKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDataTypeKind1() Dim code = <Code> struct $$S { } </Code> TestDataTypeKind(code, EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDataTypeKind2() Dim code = <Code> partial struct $$S { } partial struct S { } </Code> TestDataTypeKind(code, EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial) End Sub #End Region #Region "FullName tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName1() Dim code = <Code> struct $$S { } </Code> TestFullName(code, "S") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName2() Dim code = <Code> namespace N { struct $$S { } } </Code> TestFullName(code, "N.S") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName3() Dim code = <Code> namespace N { class C { struct $$S { } } } </Code> TestFullName(code, "N.C.S") End Sub #End Region #Region "ImplementedInterfaces tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestImplementedInterfaces1() Dim code = <Code> struct $$S : System.IDisposable { } </Code> TestImplementedInterfaces(code, IsElement("IDisposable", kind:=EnvDTE.vsCMElement.vsCMElementInterface)) End Sub #End Region #Region "Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName1() Dim code = <Code> struct $$S { } </Code> TestName(code, "S") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName2() Dim code = <Code> namespace N { struct $$S { } } </Code> TestName(code, "S") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName3() Dim code = <Code> namespace N { class C { struct $$S { } } } </Code> TestName(code, "S") End Sub #End Region #Region "Parent tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParent1() Dim code = <Code> struct $$S { } </Code> TestParent(code, IsFileCodeModel) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParent2() Dim code = <Code> namespace N { struct $$S { } } </Code> TestParent(code, IsElement("N", kind:=EnvDTE.vsCMElement.vsCMElementNamespace)) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParent3() Dim code = <Code> namespace N { class C { struct $$S { } } } </Code> TestParent(code, IsElement("C", kind:=EnvDTE.vsCMElement.vsCMElementClass)) End Sub #End Region #Region "Parts tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts1() Dim code = <Code> struct $$S { } </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts2() Dim code = <Code> partial struct $$S { } </Code> TestParts(code, 1) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParts3() Dim code = <Code> partial struct $$S { } partial struct S { } </Code> TestParts(code, 2) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> using System; struct $$S { } </Code> Dim expected = <Code> using System; [Serializable()] struct S { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> using System; [Serializable] struct $$S { } </Code> Dim expected = <Code> using System; [Serializable] [CLSCompliant(true)] struct S { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; struct $$S { } </Code> Dim expected = <Code> using System; /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] struct S { } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function #End Region #Region "AddFunction tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddFunction1() As Task Dim code = <Code> struct $$S { } </Code> Dim expected = <Code> struct S { void Goo() { } } </Code> Await TestAddFunction(code, expected, New FunctionData With {.Name = "Goo", .Type = "void"}) End Function #End Region #Region "AddImplementedInterface tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAddImplementedInterface1() Dim code = <Code> struct $$S { } </Code> TestAddImplementedInterfaceThrows(Of ArgumentException)(code, "I", Nothing) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface2() As Task Dim code = <Code> struct $$S { } interface I { } </Code> Dim expected = <Code> struct S : I { } interface I { } </Code> Await TestAddImplementedInterface(code, "I", -1, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface3() As Task Dim code = <Code> struct $$S : I { } interface I { } interface J { } </Code> Dim expected = <Code> struct S : I, J { } interface I { } interface J { } </Code> Await TestAddImplementedInterface(code, "J", -1, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface4() As Task Dim code = <Code> struct $$S : I { } interface I { } interface J { } </Code> Dim expected = <Code> struct S : J, I { } interface I { } interface J { } </Code> Await TestAddImplementedInterface(code, "J", 0, expected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImplementedInterface5() As Task Dim code = <Code> struct $$S : I, K { } interface I { } interface J { } interface K { } </Code> Dim expected = <Code> struct S : I, J, K { } interface I { } interface J { } interface K { } </Code> Await TestAddImplementedInterface(code, "J", 1, expected) End Function #End Region #Region "RemoveImplementedInterface tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveImplementedInterface1() As Task Dim code = <Code> struct $$S : I { } interface I { } </Code> Dim expected = <Code> struct S { } interface I { } </Code> Await TestRemoveImplementedInterface(code, "I", expected) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> struct $$Goo { } </Code> Dim expected = <Code> struct Bar { } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> struct $$S { } </Code> TestPropertyDescriptors(Of EnvDTE80.CodeStruct2)(code) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/EditorFeatures/TestUtilities/AutomaticCompletion/AbstractAutomaticBraceCompletionTests.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.Linq; using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.BraceCompletion; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion { [UseExportProvider] public abstract class AbstractAutomaticBraceCompletionTests { internal static void CheckStart(IBraceCompletionSession session, bool expectValidSession = true) { Type(session, session.OpeningBrace.ToString()); session.Start(); if (expectValidSession) { var closingPoint = session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot).Subtract(1); Assert.Equal(closingPoint.GetChar(), session.ClosingBrace); } else { Assert.Null(session.OpeningPoint); Assert.Null(session.ClosingPoint); } } internal static void CheckBackspace(IBraceCompletionSession session) { session.TextView.TryMoveCaretToAndEnsureVisible(session.OpeningPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot).Add(1)); session.PreBackspace(out var handled); if (!handled) { session.PostBackspace(); } Assert.Null(session.OpeningPoint); Assert.Null(session.ClosingPoint); } internal static void CheckTab(IBraceCompletionSession session, bool allowTab = true) { session.PreTab(out var handled); if (!handled) { session.PostTab(); } var caret = session.TextView.GetCaretPoint(session.SubjectBuffer).Value; if (allowTab) { Assert.Equal(session.ClosingPoint.GetPosition(session.SubjectBuffer.CurrentSnapshot), caret.Position); } else { Assert.True(caret.Position < session.ClosingPoint.GetPosition(session.SubjectBuffer.CurrentSnapshot)); } } internal static void CheckReturn(IBraceCompletionSession session, int indentation, string result = null) { session.PreReturn(out var handled); Type(session, Environment.NewLine); if (!handled) { session.PostReturn(); } var virtualCaret = session.TextView.GetVirtualCaretPoint(session.SubjectBuffer).Value; Assert.True(indentation == virtualCaret.VirtualSpaces, $"Expected indentation was {indentation}, but the actual indentation was {virtualCaret.VirtualSpaces}"); if (result != null) { AssertEx.EqualOrDiff(result, session.SubjectBuffer.CurrentSnapshot.GetText()); } } internal static void CheckText(IBraceCompletionSession session, string result) => Assert.Equal(result, session.SubjectBuffer.CurrentSnapshot.GetText()); internal static void CheckReturnOnNonEmptyLine(IBraceCompletionSession session, int expectedVirtualSpace) { session.PreReturn(out var handled); Type(session, Environment.NewLine); if (!handled) { session.PostReturn(); } var virtualCaret = session.TextView.GetVirtualCaretPoint(session.SubjectBuffer).Value; Assert.Equal(expectedVirtualSpace, virtualCaret.VirtualSpaces); } internal static void CheckOverType(IBraceCompletionSession session, bool allowOverType = true) { var preClosingPoint = session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot); Assert.Equal(session.ClosingBrace, preClosingPoint.Subtract(1).GetChar()); session.PreOverType(out var handled); if (!handled) { session.PostOverType(); } var postClosingPoint = session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot); Assert.Equal(postClosingPoint.Subtract(1).GetChar(), session.ClosingBrace); var caret = session.TextView.GetCaretPoint(session.SubjectBuffer).Value; if (allowOverType) { Assert.Equal(postClosingPoint.Position, caret.Position); } else { Assert.True(caret.Position < postClosingPoint.Position); } } internal static void Type(IBraceCompletionSession session, string text) { var buffer = session.SubjectBuffer; var caret = session.TextView.GetCaretPoint(buffer).Value; using (var edit = buffer.CreateEdit()) { edit.Insert(caret.Position, text); edit.Apply(); } } internal static Holder CreateSession(TestWorkspace workspace, char opening, char closing, Dictionary<OptionKey2, object> changedOptionSet = null) { if (changedOptionSet != null) { var options = workspace.Options; foreach (var entry in changedOptionSet) { options = options.WithChangedOption(entry.Key, entry.Value); } workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options)); } var document = workspace.Documents.First(); var provider = Assert.IsType<BraceCompletionSessionProvider>(workspace.ExportProvider.GetExportedValue<IBraceCompletionSessionProvider>()); var openingPoint = new SnapshotPoint(document.GetTextBuffer().CurrentSnapshot, document.CursorPosition.Value); if (provider.TryCreateSession(document.GetTextView(), openingPoint, opening, closing, out var session)) { return new Holder(workspace, session); } workspace.Dispose(); return null; } internal class Holder : IDisposable { public TestWorkspace Workspace { get; } public IBraceCompletionSession Session { get; } public Holder(TestWorkspace workspace, IBraceCompletionSession session) { this.Workspace = workspace; this.Session = session; } public void Dispose() => this.Workspace.Dispose(); } } }
// 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.Linq; using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.BraceCompletion; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion { [UseExportProvider] public abstract class AbstractAutomaticBraceCompletionTests { internal static void CheckStart(IBraceCompletionSession session, bool expectValidSession = true) { Type(session, session.OpeningBrace.ToString()); session.Start(); if (expectValidSession) { var closingPoint = session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot).Subtract(1); Assert.Equal(closingPoint.GetChar(), session.ClosingBrace); } else { Assert.Null(session.OpeningPoint); Assert.Null(session.ClosingPoint); } } internal static void CheckBackspace(IBraceCompletionSession session) { session.TextView.TryMoveCaretToAndEnsureVisible(session.OpeningPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot).Add(1)); session.PreBackspace(out var handled); if (!handled) { session.PostBackspace(); } Assert.Null(session.OpeningPoint); Assert.Null(session.ClosingPoint); } internal static void CheckTab(IBraceCompletionSession session, bool allowTab = true) { session.PreTab(out var handled); if (!handled) { session.PostTab(); } var caret = session.TextView.GetCaretPoint(session.SubjectBuffer).Value; if (allowTab) { Assert.Equal(session.ClosingPoint.GetPosition(session.SubjectBuffer.CurrentSnapshot), caret.Position); } else { Assert.True(caret.Position < session.ClosingPoint.GetPosition(session.SubjectBuffer.CurrentSnapshot)); } } internal static void CheckReturn(IBraceCompletionSession session, int indentation, string result = null) { session.PreReturn(out var handled); Type(session, Environment.NewLine); if (!handled) { session.PostReturn(); } var virtualCaret = session.TextView.GetVirtualCaretPoint(session.SubjectBuffer).Value; Assert.True(indentation == virtualCaret.VirtualSpaces, $"Expected indentation was {indentation}, but the actual indentation was {virtualCaret.VirtualSpaces}"); if (result != null) { AssertEx.EqualOrDiff(result, session.SubjectBuffer.CurrentSnapshot.GetText()); } } internal static void CheckText(IBraceCompletionSession session, string result) => Assert.Equal(result, session.SubjectBuffer.CurrentSnapshot.GetText()); internal static void CheckReturnOnNonEmptyLine(IBraceCompletionSession session, int expectedVirtualSpace) { session.PreReturn(out var handled); Type(session, Environment.NewLine); if (!handled) { session.PostReturn(); } var virtualCaret = session.TextView.GetVirtualCaretPoint(session.SubjectBuffer).Value; Assert.Equal(expectedVirtualSpace, virtualCaret.VirtualSpaces); } internal static void CheckOverType(IBraceCompletionSession session, bool allowOverType = true) { var preClosingPoint = session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot); Assert.Equal(session.ClosingBrace, preClosingPoint.Subtract(1).GetChar()); session.PreOverType(out var handled); if (!handled) { session.PostOverType(); } var postClosingPoint = session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot); Assert.Equal(postClosingPoint.Subtract(1).GetChar(), session.ClosingBrace); var caret = session.TextView.GetCaretPoint(session.SubjectBuffer).Value; if (allowOverType) { Assert.Equal(postClosingPoint.Position, caret.Position); } else { Assert.True(caret.Position < postClosingPoint.Position); } } internal static void Type(IBraceCompletionSession session, string text) { var buffer = session.SubjectBuffer; var caret = session.TextView.GetCaretPoint(buffer).Value; using (var edit = buffer.CreateEdit()) { edit.Insert(caret.Position, text); edit.Apply(); } } internal static Holder CreateSession(TestWorkspace workspace, char opening, char closing, Dictionary<OptionKey2, object> changedOptionSet = null) { if (changedOptionSet != null) { var options = workspace.Options; foreach (var entry in changedOptionSet) { options = options.WithChangedOption(entry.Key, entry.Value); } workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options)); } var document = workspace.Documents.First(); var provider = Assert.IsType<BraceCompletionSessionProvider>(workspace.ExportProvider.GetExportedValue<IBraceCompletionSessionProvider>()); var openingPoint = new SnapshotPoint(document.GetTextBuffer().CurrentSnapshot, document.CursorPosition.Value); if (provider.TryCreateSession(document.GetTextView(), openingPoint, opening, closing, out var session)) { return new Holder(workspace, session); } workspace.Dispose(); return null; } internal class Holder : IDisposable { public TestWorkspace Workspace { get; } public IBraceCompletionSession Session { get; } public Holder(TestWorkspace workspace, IBraceCompletionSession session) { this.Workspace = workspace; this.Session = session; } public void Dispose() => this.Workspace.Dispose(); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Core/Portable/SourceFileResolver.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.CodeAnalysis; using System.IO; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Resolves references to source files specified in source code. /// </summary> public class SourceFileResolver : SourceReferenceResolver, IEquatable<SourceFileResolver> { public static SourceFileResolver Default { get; } = new SourceFileResolver(ImmutableArray<string>.Empty, baseDirectory: null); private readonly string? _baseDirectory; private readonly ImmutableArray<string> _searchPaths; private readonly ImmutableArray<KeyValuePair<string, string>> _pathMap; public SourceFileResolver(IEnumerable<string> searchPaths, string? baseDirectory) : this(searchPaths.AsImmutableOrNull(), baseDirectory) { } public SourceFileResolver(ImmutableArray<string> searchPaths, string? baseDirectory) : this(searchPaths, baseDirectory, ImmutableArray<KeyValuePair<string, string>>.Empty) { } public SourceFileResolver( ImmutableArray<string> searchPaths, string? baseDirectory, ImmutableArray<KeyValuePair<string, string>> pathMap) { if (searchPaths.IsDefault) { throw new ArgumentNullException(nameof(searchPaths)); } if (baseDirectory != null && PathUtilities.GetPathKind(baseDirectory) != PathKind.Absolute) { throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, nameof(baseDirectory)); } _baseDirectory = baseDirectory; _searchPaths = searchPaths; // The previous public API required paths to not end with a path separator. // This broke handling of root paths (e.g. "/" cannot be represented), so // the new requirement is for paths to always end with a path separator. // However, because this is a public API, both conventions must be allowed, // so normalize the paths here (instead of enforcing end-with-sep). if (!pathMap.IsDefaultOrEmpty) { var pathMapBuilder = ArrayBuilder<KeyValuePair<string, string>>.GetInstance(pathMap.Length); foreach (var (key, value) in pathMap) { if (key == null || key.Length == 0) { throw new ArgumentException(CodeAnalysisResources.EmptyKeyInPathMap, nameof(pathMap)); } if (value == null) { throw new ArgumentException(CodeAnalysisResources.NullValueInPathMap, nameof(pathMap)); } var normalizedKey = PathUtilities.EnsureTrailingSeparator(key); var normalizedValue = PathUtilities.EnsureTrailingSeparator(value); pathMapBuilder.Add(new KeyValuePair<string, string>(normalizedKey, normalizedValue)); } _pathMap = pathMapBuilder.ToImmutableAndFree(); } else { _pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty; } } public string? BaseDirectory => _baseDirectory; public ImmutableArray<string> SearchPaths => _searchPaths; public ImmutableArray<KeyValuePair<string, string>> PathMap => _pathMap; public override string? NormalizePath(string path, string? baseFilePath) { string? normalizedPath = FileUtilities.NormalizeRelativePath(path, baseFilePath, _baseDirectory); return (normalizedPath == null || _pathMap.IsDefaultOrEmpty) ? normalizedPath : PathUtilities.NormalizePathPrefix(normalizedPath, _pathMap); } public override string? ResolveReference(string path, string? baseFilePath) { string? resolvedPath = FileUtilities.ResolveRelativePath(path, baseFilePath, _baseDirectory, _searchPaths, FileExists); if (resolvedPath == null) { return null; } return FileUtilities.TryNormalizeAbsolutePath(resolvedPath); } public override Stream OpenRead(string resolvedPath) { CompilerPathUtilities.RequireAbsolutePath(resolvedPath, nameof(resolvedPath)); return FileUtilities.OpenRead(resolvedPath); } protected virtual bool FileExists([NotNullWhen(true)] string? resolvedPath) { return File.Exists(resolvedPath); } public override bool Equals(object? obj) { // Explicitly check that we're not comparing against a derived type if (obj == null || GetType() != obj.GetType()) { return false; } return Equals((SourceFileResolver)obj); } public bool Equals(SourceFileResolver? other) { if (other is null) { return false; } return string.Equals(_baseDirectory, other._baseDirectory, StringComparison.Ordinal) && _searchPaths.SequenceEqual(other._searchPaths, StringComparer.Ordinal) && _pathMap.SequenceEqual(other._pathMap); } public override int GetHashCode() { return Hash.Combine(_baseDirectory != null ? StringComparer.Ordinal.GetHashCode(_baseDirectory) : 0, Hash.Combine(Hash.CombineValues(_searchPaths, StringComparer.Ordinal), Hash.CombineValues(_pathMap))); } } }
// 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.CodeAnalysis; using System.IO; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Resolves references to source files specified in source code. /// </summary> public class SourceFileResolver : SourceReferenceResolver, IEquatable<SourceFileResolver> { public static SourceFileResolver Default { get; } = new SourceFileResolver(ImmutableArray<string>.Empty, baseDirectory: null); private readonly string? _baseDirectory; private readonly ImmutableArray<string> _searchPaths; private readonly ImmutableArray<KeyValuePair<string, string>> _pathMap; public SourceFileResolver(IEnumerable<string> searchPaths, string? baseDirectory) : this(searchPaths.AsImmutableOrNull(), baseDirectory) { } public SourceFileResolver(ImmutableArray<string> searchPaths, string? baseDirectory) : this(searchPaths, baseDirectory, ImmutableArray<KeyValuePair<string, string>>.Empty) { } public SourceFileResolver( ImmutableArray<string> searchPaths, string? baseDirectory, ImmutableArray<KeyValuePair<string, string>> pathMap) { if (searchPaths.IsDefault) { throw new ArgumentNullException(nameof(searchPaths)); } if (baseDirectory != null && PathUtilities.GetPathKind(baseDirectory) != PathKind.Absolute) { throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, nameof(baseDirectory)); } _baseDirectory = baseDirectory; _searchPaths = searchPaths; // The previous public API required paths to not end with a path separator. // This broke handling of root paths (e.g. "/" cannot be represented), so // the new requirement is for paths to always end with a path separator. // However, because this is a public API, both conventions must be allowed, // so normalize the paths here (instead of enforcing end-with-sep). if (!pathMap.IsDefaultOrEmpty) { var pathMapBuilder = ArrayBuilder<KeyValuePair<string, string>>.GetInstance(pathMap.Length); foreach (var (key, value) in pathMap) { if (key == null || key.Length == 0) { throw new ArgumentException(CodeAnalysisResources.EmptyKeyInPathMap, nameof(pathMap)); } if (value == null) { throw new ArgumentException(CodeAnalysisResources.NullValueInPathMap, nameof(pathMap)); } var normalizedKey = PathUtilities.EnsureTrailingSeparator(key); var normalizedValue = PathUtilities.EnsureTrailingSeparator(value); pathMapBuilder.Add(new KeyValuePair<string, string>(normalizedKey, normalizedValue)); } _pathMap = pathMapBuilder.ToImmutableAndFree(); } else { _pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty; } } public string? BaseDirectory => _baseDirectory; public ImmutableArray<string> SearchPaths => _searchPaths; public ImmutableArray<KeyValuePair<string, string>> PathMap => _pathMap; public override string? NormalizePath(string path, string? baseFilePath) { string? normalizedPath = FileUtilities.NormalizeRelativePath(path, baseFilePath, _baseDirectory); return (normalizedPath == null || _pathMap.IsDefaultOrEmpty) ? normalizedPath : PathUtilities.NormalizePathPrefix(normalizedPath, _pathMap); } public override string? ResolveReference(string path, string? baseFilePath) { string? resolvedPath = FileUtilities.ResolveRelativePath(path, baseFilePath, _baseDirectory, _searchPaths, FileExists); if (resolvedPath == null) { return null; } return FileUtilities.TryNormalizeAbsolutePath(resolvedPath); } public override Stream OpenRead(string resolvedPath) { CompilerPathUtilities.RequireAbsolutePath(resolvedPath, nameof(resolvedPath)); return FileUtilities.OpenRead(resolvedPath); } protected virtual bool FileExists([NotNullWhen(true)] string? resolvedPath) { return File.Exists(resolvedPath); } public override bool Equals(object? obj) { // Explicitly check that we're not comparing against a derived type if (obj == null || GetType() != obj.GetType()) { return false; } return Equals((SourceFileResolver)obj); } public bool Equals(SourceFileResolver? other) { if (other is null) { return false; } return string.Equals(_baseDirectory, other._baseDirectory, StringComparison.Ordinal) && _searchPaths.SequenceEqual(other._searchPaths, StringComparer.Ordinal) && _pathMap.SequenceEqual(other._pathMap); } public override int GetHashCode() { return Hash.Combine(_baseDirectory != null ? StringComparer.Ordinal.GetHashCode(_baseDirectory) : 0, Hash.Combine(Hash.CombineValues(_searchPaths, StringComparer.Ordinal), Hash.CombineValues(_pathMap))); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/GeneratedNames.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.Collections.Immutable Imports System.Globalization Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Helper class to generate synthesized names. ''' </summary> Friend NotInheritable Class GeneratedNames Friend Const DotReplacementInTypeNames As Char = "-"c Private Const s_methodNameSeparator As Char = "_"c Private Const s_idSeparator As Char = "-"c Private Const s_generationSeparator As Char = "#"c ''' <summary> ''' Generates the name of a state machine's type. ''' </summary> Public Shared Function MakeStateMachineTypeName(methodName As String, methodOrdinal As Integer, generation As Integer) As String Debug.Assert(methodOrdinal >= -1) Return MakeMethodScopedSynthesizedName(StringConstants.StateMachineTypeNamePrefix, methodOrdinal, generation, methodName, isTypeName:=True) End Function ''' <summary> ''' Generates the name of a state machine 'state' field ''' </summary> Public Shared Function MakeStateMachineStateFieldName() As String Return StringConstants.StateMachineStateFieldName End Function Public Shared Function MakeBaseMethodWrapperName(methodName As String, isMyBase As Boolean) As String Return StringConstants.BaseMethodWrapperNamePrefix & methodName & If(isMyBase, "_MyBase", "_MyClass") End Function Public Shared Function ReusableHoistedLocalFieldName(number As Integer) As String Return StringConstants.ReusableHoistedLocalFieldName & StringExtensions.GetNumeral(number) End Function Public Shared Function MakeStaticLambdaDisplayClassName(methodOrdinal As Integer, generation As Integer) As String Debug.Assert(methodOrdinal >= -1) Debug.Assert(generation >= 0) Return MakeMethodScopedSynthesizedName(StringConstants.DisplayClassPrefix, methodOrdinal, generation) End Function Friend Shared Function MakeLambdaDisplayClassName(methodOrdinal As Integer, generation As Integer, closureOrdinal As Integer, closureGeneration As Integer, isDelegateRelaxation As Boolean) As String Debug.Assert(closureOrdinal >= 0) Debug.Assert(methodOrdinal >= 0) Debug.Assert(generation >= 0) Dim prefix = If(isDelegateRelaxation, StringConstants.DelegateRelaxationDisplayClassPrefix, StringConstants.DisplayClassPrefix) Return MakeMethodScopedSynthesizedName(prefix, methodOrdinal, generation, entityOrdinal:=closureOrdinal, entityGeneration:=closureGeneration, isTypeName:=True) End Function Friend Shared Function MakeDisplayClassGenericParameterName(parameterIndex As Integer) As String Return StringConstants.DisplayClassGenericParameterNamePrefix & StringExtensions.GetNumeral(parameterIndex) End Function Friend Shared Function MakeLambdaMethodName(methodOrdinal As Integer, generation As Integer, lambdaOrdinal As Integer, lambdaGeneration As Integer, lambdaKind As SynthesizedLambdaKind) As String Debug.Assert(methodOrdinal >= -1) Debug.Assert(lambdaOrdinal >= 0) Dim prefix = If(lambdaKind = SynthesizedLambdaKind.DelegateRelaxationStub, StringConstants.DelegateRelaxationMethodNamePrefix, StringConstants.LambdaMethodNamePrefix) Return MakeMethodScopedSynthesizedName(prefix, methodOrdinal, generation, entityOrdinal:=lambdaOrdinal, entityGeneration:=lambdaGeneration) End Function ''' <summary> ''' Generates the name of a static lambda display class instance cache ''' </summary> Public Shared Function MakeCachedFrameInstanceName() As String Return StringConstants.LambdaCacheFieldPrefix End Function Friend Shared Function MakeLambdaCacheFieldName(methodOrdinal As Integer, generation As Integer, lambdaOrdinal As Integer, lambdaGeneration As Integer, lambdaKind As SynthesizedLambdaKind) As String Debug.Assert(methodOrdinal >= -1) Debug.Assert(lambdaOrdinal >= 0) Dim prefix = If(lambdaKind = SynthesizedLambdaKind.DelegateRelaxationStub, StringConstants.DelegateRelaxationCacheFieldPrefix, StringConstants.LambdaCacheFieldPrefix) Return MakeMethodScopedSynthesizedName(prefix, methodOrdinal, generation, entityOrdinal:=lambdaOrdinal, entityGeneration:=lambdaGeneration) End Function Friend Shared Function MakeDelegateRelaxationParameterName(parameterIndex As Integer) As String Return StringConstants.DelegateStubParameterPrefix & StringExtensions.GetNumeral(parameterIndex) End Function Private Shared Function MakeMethodScopedSynthesizedName(prefix As String, methodOrdinal As Integer, methodGeneration As Integer, Optional methodNameOpt As String = Nothing, Optional entityOrdinal As Integer = -1, Optional entityGeneration As Integer = -1, Optional isTypeName As Boolean = False) As String Debug.Assert(methodOrdinal >= -1) Debug.Assert(methodGeneration >= 0 OrElse methodGeneration = -1 AndAlso methodOrdinal = -1) Debug.Assert(entityOrdinal >= -1) Debug.Assert(entityGeneration >= 0 OrElse entityGeneration = -1 AndAlso entityOrdinal = -1) Debug.Assert(entityGeneration = -1 OrElse entityGeneration >= methodGeneration) Dim result = PooledStringBuilder.GetInstance() Dim builder = result.Builder builder.Append(prefix) If methodOrdinal >= 0 Then builder.Append(methodOrdinal) If methodGeneration > 0 Then builder.Append(s_generationSeparator) builder.Append(methodGeneration) End If End If If entityOrdinal >= 0 Then If methodOrdinal >= 0 Then ' Can't use underscore since name parser uses it to find the method name. builder.Append(s_idSeparator) End If builder.Append(entityOrdinal) If entityGeneration > 0 Then builder.Append(s_generationSeparator) builder.Append(entityGeneration) End If End If If methodNameOpt IsNot Nothing Then builder.Append(s_methodNameSeparator) builder.Append(methodNameOpt) ' CLR generally allows names with dots, however some APIs like IMetaDataImport ' can only return full type names combined with namespaces. ' see: http://msdn.microsoft.com/en-us/library/ms230143.aspx (IMetaDataImport::GetTypeDefProps) ' When working with such APIs, names with dots become ambiguous since metadata ' consumer cannot figure where namespace ends and actual type name starts. ' Therefore it is a good practice to avoid type names with dots. If isTypeName Then builder.Replace("."c, DotReplacementInTypeNames) End If End If Return result.ToStringAndFree() End Function Public Shared Function TryParseStateMachineTypeName(stateMachineTypeName As String, <Out> ByRef methodName As String) As Boolean If Not stateMachineTypeName.StartsWith(StringConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal) Then Return False End If Dim prefixLength As Integer = StringConstants.StateMachineTypeNamePrefix.Length Dim separatorPos = stateMachineTypeName.IndexOf(s_methodNameSeparator, prefixLength) If separatorPos < 0 OrElse separatorPos = stateMachineTypeName.Length - 1 Then Return False End If methodName = stateMachineTypeName.Substring(separatorPos + 1) Return True End Function ''' <summary> ''' Generates the name of a state machine 'builder' field ''' </summary> Public Shared Function MakeStateMachineBuilderFieldName() As String Return StringConstants.StateMachineBuilderFieldName End Function ''' <summary> ''' Generates the name of a field that backs Current property ''' </summary> Public Shared Function MakeIteratorCurrentFieldName() As String Return StringConstants.IteratorCurrentFieldName End Function ''' <summary> ''' Generates the name of a state machine's awaiter field ''' </summary> Public Shared Function MakeStateMachineAwaiterFieldName(index As Integer) As String Return StringConstants.StateMachineAwaiterFieldPrefix & StringExtensions.GetNumeral(index) End Function ''' <summary> ''' Generates the name of a state machine's parameter name ''' </summary> Public Shared Function MakeStateMachineParameterName(paramName As String) As String Return StringConstants.HoistedUserVariablePrefix & paramName End Function ''' <summary> ''' Generates the name of a state machine's parameter name ''' </summary> Public Shared Function MakeIteratorParameterProxyName(paramName As String) As String Return StringConstants.IteratorParameterProxyPrefix & paramName End Function ''' <summary> ''' Generates the name of a field where initial thread ID is stored ''' </summary> Public Shared Function MakeIteratorInitialThreadIdName() As String Return StringConstants.IteratorInitialThreadIdName End Function ''' <summary> ''' Try to parse the local (or parameter) name and return <paramref name="variableName"/> if successful. ''' </summary> Public Shared Function TryParseHoistedUserVariableName(proxyName As String, <Out> ByRef variableName As String) As Boolean variableName = Nothing Dim prefixLen As Integer = StringConstants.HoistedUserVariablePrefix.Length If proxyName.Length <= prefixLen Then Return False End If ' All names should start with "$VB$Local_" If Not proxyName.StartsWith(StringConstants.HoistedUserVariablePrefix, StringComparison.Ordinal) Then Return False End If variableName = proxyName.Substring(prefixLen) Return True End Function ''' <summary> ''' Try to parse the local name and return <paramref name="variableName"/> and <paramref name="index"/> if successful. ''' </summary> Public Shared Function TryParseStateMachineHoistedUserVariableName(proxyName As String, <Out> ByRef variableName As String, <Out()> ByRef index As Integer) As Boolean variableName = Nothing index = 0 ' All names should start with "$VB$ResumableLocal_" If Not proxyName.StartsWith(StringConstants.StateMachineHoistedUserVariablePrefix, StringComparison.Ordinal) Then Return False End If Dim prefixLen As Integer = StringConstants.StateMachineHoistedUserVariablePrefix.Length Dim separator As Integer = proxyName.LastIndexOf("$"c) If separator <= prefixLen Then Return False End If variableName = proxyName.Substring(prefixLen, separator - prefixLen) Return Integer.TryParse(proxyName.Substring(separator + 1), NumberStyles.None, CultureInfo.InvariantCulture, index) End Function ''' <summary> ''' Generates the name of a state machine field name for captured me reference ''' </summary> Public Shared Function MakeStateMachineCapturedMeName() As String Return StringConstants.HoistedMeName End Function ''' <summary> ''' Generates the name of a state machine field name for captured me reference of lambda closure ''' </summary> Public Shared Function MakeStateMachineCapturedClosureMeName(closureName As String) As String Return StringConstants.HoistedSpecialVariablePrefix & closureName End Function Friend Const AnonymousTypeOrDelegateCommonPrefix = "VB$Anonymous" Friend Const AnonymousTypeTemplateNamePrefix = AnonymousTypeOrDelegateCommonPrefix & "Type_" Friend Const AnonymousDelegateTemplateNamePrefix = AnonymousTypeOrDelegateCommonPrefix & "Delegate_" Friend Shared Function MakeAnonymousTypeTemplateName(prefix As String, index As Integer, submissionSlotIndex As Integer, moduleId As String) As String Return If(submissionSlotIndex >= 0, String.Format("{0}{1}_{2}{3}", prefix, submissionSlotIndex, index, moduleId), String.Format("{0}{1}{2}", prefix, index, moduleId)) End Function Friend Shared Function TryParseAnonymousTypeTemplateName(prefix As String, name As String, <Out()> ByRef index As Integer) As Boolean ' No callers require anonymous types from net modules, ' so names with module id are ignored. If name.StartsWith(prefix, StringComparison.Ordinal) AndAlso Integer.TryParse(name.Substring(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, index) Then Return True End If index = -1 Return False End Function Friend Shared Function MakeSynthesizedLocalName(kind As SynthesizedLocalKind, ByRef uniqueId As Integer) As String Debug.Assert(kind.IsLongLived()) ' The following variables have to be named, EE depends on the name format. Dim name As String Select Case kind Case SynthesizedLocalKind.LambdaDisplayClass name = MakeLambdaDisplayClassStorageName(uniqueId) uniqueId += 1 Case SynthesizedLocalKind.With ' Dev12 didn't name the local. We do so that we can do better job in EE evaluating With statements. name = StringConstants.HoistedWithLocalPrefix & StringExtensions.GetNumeral(uniqueId) uniqueId += 1 Case Else name = Nothing End Select Return name End Function Friend Shared Function MakeLambdaDisplayClassStorageName(uniqueId As Integer) As String Return StringConstants.ClosureVariablePrefix & StringExtensions.GetNumeral(uniqueId) End Function Friend Shared Function MakeSignatureString(signature As Byte()) As String Dim builder = PooledStringBuilder.GetInstance() For Each b In signature ' Note the format of each byte is not fixed width, so the resulting string may be ' ambiguous. And since this method Is used to generate field names for static ' locals, the same field name may be generated for two locals with the same ' local name in overloaded methods. The native compiler has the same behavior. ' Using a fixed width format {0:X2} would solve this but since the EE relies on ' the format for recognizing static locals, that would be a breaking change. builder.Builder.AppendFormat("{0:X}", b) Next Return builder.ToStringAndFree() End Function Friend Shared Function MakeStaticLocalFieldName( methodName As String, methodSignature As String, localName As String) As String Return String.Format(StringConstants.StaticLocalFieldNamePrefix & "{0}${1}${2}", methodName, methodSignature, localName) End Function Friend Shared Function TryParseStaticLocalFieldName( fieldName As String, <Out> ByRef methodName As String, <Out> ByRef methodSignature As String, <Out> ByRef localName As String) As Boolean If fieldName.StartsWith(StringConstants.StaticLocalFieldNamePrefix, StringComparison.Ordinal) Then Dim parts = fieldName.Split("$"c) If parts.Length = 5 Then methodName = parts(2) methodSignature = parts(3) localName = parts(4) Return True End If End If methodName = Nothing methodSignature = Nothing localName = Nothing Return False End Function ' Extracts the slot index from a name of a field that stores hoisted variables or awaiters. ' Such a name ends with "$prefix{slot index}". ' Returned slot index is >= 0. Friend Shared Function TryParseSlotIndex(prefix As String, fieldName As String, <Out> ByRef slotIndex As Integer) As Boolean If fieldName.StartsWith(prefix, StringComparison.Ordinal) AndAlso Integer.TryParse(fieldName.Substring(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, slotIndex) Then Return True End If slotIndex = -1 Return False 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.Collections.Immutable Imports System.Globalization Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Helper class to generate synthesized names. ''' </summary> Friend NotInheritable Class GeneratedNames Friend Const DotReplacementInTypeNames As Char = "-"c Private Const s_methodNameSeparator As Char = "_"c Private Const s_idSeparator As Char = "-"c Private Const s_generationSeparator As Char = "#"c ''' <summary> ''' Generates the name of a state machine's type. ''' </summary> Public Shared Function MakeStateMachineTypeName(methodName As String, methodOrdinal As Integer, generation As Integer) As String Debug.Assert(methodOrdinal >= -1) Return MakeMethodScopedSynthesizedName(StringConstants.StateMachineTypeNamePrefix, methodOrdinal, generation, methodName, isTypeName:=True) End Function ''' <summary> ''' Generates the name of a state machine 'state' field ''' </summary> Public Shared Function MakeStateMachineStateFieldName() As String Return StringConstants.StateMachineStateFieldName End Function Public Shared Function MakeBaseMethodWrapperName(methodName As String, isMyBase As Boolean) As String Return StringConstants.BaseMethodWrapperNamePrefix & methodName & If(isMyBase, "_MyBase", "_MyClass") End Function Public Shared Function ReusableHoistedLocalFieldName(number As Integer) As String Return StringConstants.ReusableHoistedLocalFieldName & StringExtensions.GetNumeral(number) End Function Public Shared Function MakeStaticLambdaDisplayClassName(methodOrdinal As Integer, generation As Integer) As String Debug.Assert(methodOrdinal >= -1) Debug.Assert(generation >= 0) Return MakeMethodScopedSynthesizedName(StringConstants.DisplayClassPrefix, methodOrdinal, generation) End Function Friend Shared Function MakeLambdaDisplayClassName(methodOrdinal As Integer, generation As Integer, closureOrdinal As Integer, closureGeneration As Integer, isDelegateRelaxation As Boolean) As String Debug.Assert(closureOrdinal >= 0) Debug.Assert(methodOrdinal >= 0) Debug.Assert(generation >= 0) Dim prefix = If(isDelegateRelaxation, StringConstants.DelegateRelaxationDisplayClassPrefix, StringConstants.DisplayClassPrefix) Return MakeMethodScopedSynthesizedName(prefix, methodOrdinal, generation, entityOrdinal:=closureOrdinal, entityGeneration:=closureGeneration, isTypeName:=True) End Function Friend Shared Function MakeDisplayClassGenericParameterName(parameterIndex As Integer) As String Return StringConstants.DisplayClassGenericParameterNamePrefix & StringExtensions.GetNumeral(parameterIndex) End Function Friend Shared Function MakeLambdaMethodName(methodOrdinal As Integer, generation As Integer, lambdaOrdinal As Integer, lambdaGeneration As Integer, lambdaKind As SynthesizedLambdaKind) As String Debug.Assert(methodOrdinal >= -1) Debug.Assert(lambdaOrdinal >= 0) Dim prefix = If(lambdaKind = SynthesizedLambdaKind.DelegateRelaxationStub, StringConstants.DelegateRelaxationMethodNamePrefix, StringConstants.LambdaMethodNamePrefix) Return MakeMethodScopedSynthesizedName(prefix, methodOrdinal, generation, entityOrdinal:=lambdaOrdinal, entityGeneration:=lambdaGeneration) End Function ''' <summary> ''' Generates the name of a static lambda display class instance cache ''' </summary> Public Shared Function MakeCachedFrameInstanceName() As String Return StringConstants.LambdaCacheFieldPrefix End Function Friend Shared Function MakeLambdaCacheFieldName(methodOrdinal As Integer, generation As Integer, lambdaOrdinal As Integer, lambdaGeneration As Integer, lambdaKind As SynthesizedLambdaKind) As String Debug.Assert(methodOrdinal >= -1) Debug.Assert(lambdaOrdinal >= 0) Dim prefix = If(lambdaKind = SynthesizedLambdaKind.DelegateRelaxationStub, StringConstants.DelegateRelaxationCacheFieldPrefix, StringConstants.LambdaCacheFieldPrefix) Return MakeMethodScopedSynthesizedName(prefix, methodOrdinal, generation, entityOrdinal:=lambdaOrdinal, entityGeneration:=lambdaGeneration) End Function Friend Shared Function MakeDelegateRelaxationParameterName(parameterIndex As Integer) As String Return StringConstants.DelegateStubParameterPrefix & StringExtensions.GetNumeral(parameterIndex) End Function Private Shared Function MakeMethodScopedSynthesizedName(prefix As String, methodOrdinal As Integer, methodGeneration As Integer, Optional methodNameOpt As String = Nothing, Optional entityOrdinal As Integer = -1, Optional entityGeneration As Integer = -1, Optional isTypeName As Boolean = False) As String Debug.Assert(methodOrdinal >= -1) Debug.Assert(methodGeneration >= 0 OrElse methodGeneration = -1 AndAlso methodOrdinal = -1) Debug.Assert(entityOrdinal >= -1) Debug.Assert(entityGeneration >= 0 OrElse entityGeneration = -1 AndAlso entityOrdinal = -1) Debug.Assert(entityGeneration = -1 OrElse entityGeneration >= methodGeneration) Dim result = PooledStringBuilder.GetInstance() Dim builder = result.Builder builder.Append(prefix) If methodOrdinal >= 0 Then builder.Append(methodOrdinal) If methodGeneration > 0 Then builder.Append(s_generationSeparator) builder.Append(methodGeneration) End If End If If entityOrdinal >= 0 Then If methodOrdinal >= 0 Then ' Can't use underscore since name parser uses it to find the method name. builder.Append(s_idSeparator) End If builder.Append(entityOrdinal) If entityGeneration > 0 Then builder.Append(s_generationSeparator) builder.Append(entityGeneration) End If End If If methodNameOpt IsNot Nothing Then builder.Append(s_methodNameSeparator) builder.Append(methodNameOpt) ' CLR generally allows names with dots, however some APIs like IMetaDataImport ' can only return full type names combined with namespaces. ' see: http://msdn.microsoft.com/en-us/library/ms230143.aspx (IMetaDataImport::GetTypeDefProps) ' When working with such APIs, names with dots become ambiguous since metadata ' consumer cannot figure where namespace ends and actual type name starts. ' Therefore it is a good practice to avoid type names with dots. If isTypeName Then builder.Replace("."c, DotReplacementInTypeNames) End If End If Return result.ToStringAndFree() End Function Public Shared Function TryParseStateMachineTypeName(stateMachineTypeName As String, <Out> ByRef methodName As String) As Boolean If Not stateMachineTypeName.StartsWith(StringConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal) Then Return False End If Dim prefixLength As Integer = StringConstants.StateMachineTypeNamePrefix.Length Dim separatorPos = stateMachineTypeName.IndexOf(s_methodNameSeparator, prefixLength) If separatorPos < 0 OrElse separatorPos = stateMachineTypeName.Length - 1 Then Return False End If methodName = stateMachineTypeName.Substring(separatorPos + 1) Return True End Function ''' <summary> ''' Generates the name of a state machine 'builder' field ''' </summary> Public Shared Function MakeStateMachineBuilderFieldName() As String Return StringConstants.StateMachineBuilderFieldName End Function ''' <summary> ''' Generates the name of a field that backs Current property ''' </summary> Public Shared Function MakeIteratorCurrentFieldName() As String Return StringConstants.IteratorCurrentFieldName End Function ''' <summary> ''' Generates the name of a state machine's awaiter field ''' </summary> Public Shared Function MakeStateMachineAwaiterFieldName(index As Integer) As String Return StringConstants.StateMachineAwaiterFieldPrefix & StringExtensions.GetNumeral(index) End Function ''' <summary> ''' Generates the name of a state machine's parameter name ''' </summary> Public Shared Function MakeStateMachineParameterName(paramName As String) As String Return StringConstants.HoistedUserVariablePrefix & paramName End Function ''' <summary> ''' Generates the name of a state machine's parameter name ''' </summary> Public Shared Function MakeIteratorParameterProxyName(paramName As String) As String Return StringConstants.IteratorParameterProxyPrefix & paramName End Function ''' <summary> ''' Generates the name of a field where initial thread ID is stored ''' </summary> Public Shared Function MakeIteratorInitialThreadIdName() As String Return StringConstants.IteratorInitialThreadIdName End Function ''' <summary> ''' Try to parse the local (or parameter) name and return <paramref name="variableName"/> if successful. ''' </summary> Public Shared Function TryParseHoistedUserVariableName(proxyName As String, <Out> ByRef variableName As String) As Boolean variableName = Nothing Dim prefixLen As Integer = StringConstants.HoistedUserVariablePrefix.Length If proxyName.Length <= prefixLen Then Return False End If ' All names should start with "$VB$Local_" If Not proxyName.StartsWith(StringConstants.HoistedUserVariablePrefix, StringComparison.Ordinal) Then Return False End If variableName = proxyName.Substring(prefixLen) Return True End Function ''' <summary> ''' Try to parse the local name and return <paramref name="variableName"/> and <paramref name="index"/> if successful. ''' </summary> Public Shared Function TryParseStateMachineHoistedUserVariableName(proxyName As String, <Out> ByRef variableName As String, <Out()> ByRef index As Integer) As Boolean variableName = Nothing index = 0 ' All names should start with "$VB$ResumableLocal_" If Not proxyName.StartsWith(StringConstants.StateMachineHoistedUserVariablePrefix, StringComparison.Ordinal) Then Return False End If Dim prefixLen As Integer = StringConstants.StateMachineHoistedUserVariablePrefix.Length Dim separator As Integer = proxyName.LastIndexOf("$"c) If separator <= prefixLen Then Return False End If variableName = proxyName.Substring(prefixLen, separator - prefixLen) Return Integer.TryParse(proxyName.Substring(separator + 1), NumberStyles.None, CultureInfo.InvariantCulture, index) End Function ''' <summary> ''' Generates the name of a state machine field name for captured me reference ''' </summary> Public Shared Function MakeStateMachineCapturedMeName() As String Return StringConstants.HoistedMeName End Function ''' <summary> ''' Generates the name of a state machine field name for captured me reference of lambda closure ''' </summary> Public Shared Function MakeStateMachineCapturedClosureMeName(closureName As String) As String Return StringConstants.HoistedSpecialVariablePrefix & closureName End Function Friend Const AnonymousTypeOrDelegateCommonPrefix = "VB$Anonymous" Friend Const AnonymousTypeTemplateNamePrefix = AnonymousTypeOrDelegateCommonPrefix & "Type_" Friend Const AnonymousDelegateTemplateNamePrefix = AnonymousTypeOrDelegateCommonPrefix & "Delegate_" Friend Shared Function MakeAnonymousTypeTemplateName(prefix As String, index As Integer, submissionSlotIndex As Integer, moduleId As String) As String Return If(submissionSlotIndex >= 0, String.Format("{0}{1}_{2}{3}", prefix, submissionSlotIndex, index, moduleId), String.Format("{0}{1}{2}", prefix, index, moduleId)) End Function Friend Shared Function TryParseAnonymousTypeTemplateName(prefix As String, name As String, <Out()> ByRef index As Integer) As Boolean ' No callers require anonymous types from net modules, ' so names with module id are ignored. If name.StartsWith(prefix, StringComparison.Ordinal) AndAlso Integer.TryParse(name.Substring(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, index) Then Return True End If index = -1 Return False End Function Friend Shared Function MakeSynthesizedLocalName(kind As SynthesizedLocalKind, ByRef uniqueId As Integer) As String Debug.Assert(kind.IsLongLived()) ' The following variables have to be named, EE depends on the name format. Dim name As String Select Case kind Case SynthesizedLocalKind.LambdaDisplayClass name = MakeLambdaDisplayClassStorageName(uniqueId) uniqueId += 1 Case SynthesizedLocalKind.With ' Dev12 didn't name the local. We do so that we can do better job in EE evaluating With statements. name = StringConstants.HoistedWithLocalPrefix & StringExtensions.GetNumeral(uniqueId) uniqueId += 1 Case Else name = Nothing End Select Return name End Function Friend Shared Function MakeLambdaDisplayClassStorageName(uniqueId As Integer) As String Return StringConstants.ClosureVariablePrefix & StringExtensions.GetNumeral(uniqueId) End Function Friend Shared Function MakeSignatureString(signature As Byte()) As String Dim builder = PooledStringBuilder.GetInstance() For Each b In signature ' Note the format of each byte is not fixed width, so the resulting string may be ' ambiguous. And since this method Is used to generate field names for static ' locals, the same field name may be generated for two locals with the same ' local name in overloaded methods. The native compiler has the same behavior. ' Using a fixed width format {0:X2} would solve this but since the EE relies on ' the format for recognizing static locals, that would be a breaking change. builder.Builder.AppendFormat("{0:X}", b) Next Return builder.ToStringAndFree() End Function Friend Shared Function MakeStaticLocalFieldName( methodName As String, methodSignature As String, localName As String) As String Return String.Format(StringConstants.StaticLocalFieldNamePrefix & "{0}${1}${2}", methodName, methodSignature, localName) End Function Friend Shared Function TryParseStaticLocalFieldName( fieldName As String, <Out> ByRef methodName As String, <Out> ByRef methodSignature As String, <Out> ByRef localName As String) As Boolean If fieldName.StartsWith(StringConstants.StaticLocalFieldNamePrefix, StringComparison.Ordinal) Then Dim parts = fieldName.Split("$"c) If parts.Length = 5 Then methodName = parts(2) methodSignature = parts(3) localName = parts(4) Return True End If End If methodName = Nothing methodSignature = Nothing localName = Nothing Return False End Function ' Extracts the slot index from a name of a field that stores hoisted variables or awaiters. ' Such a name ends with "$prefix{slot index}". ' Returned slot index is >= 0. Friend Shared Function TryParseSlotIndex(prefix As String, fieldName As String, <Out> ByRef slotIndex As Integer) As Boolean If fieldName.StartsWith(prefix, StringComparison.Ordinal) AndAlso Integer.TryParse(fieldName.Substring(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, slotIndex) Then Return True End If slotIndex = -1 Return False End Function End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/CodeStyle/BannedSymbols.txt
P:Microsoft.CodeAnalysis.Project.LanguageServices; Use 'GetExtendedLanguageServices' instead M:Microsoft.CodeAnalysis.Host.HostWorkspaceServices.GetLanguageServices(System.String); Use 'GetExtendedLanguageServices' or directly get the language service by invoking 'GetLanguageService' or 'GetRequiredLanguageService' T:Microsoft.CodeAnalysis.Options.OptionSet; 'OptionSet' is not available in CodeStyle layer. Add a using/Imports statement defining 'OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions' when preprocessor variable 'CODE_STYLE' is defined T:Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption`1; Use 'Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption2' instead T:Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions; Use 'Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions2' instead T:Microsoft.CodeAnalysis.Options.OptionKey; Use 'Microsoft.CodeAnalysis.Options.OptionKey2' instead T:Microsoft.CodeAnalysis.CodeStyle.NotificationOption; Use 'Microsoft.CodeAnalysis.CodeStyle.NotificationOption2' instead M:Microsoft.CodeAnalysis.DiagnosticDescriptor.#ctor(System.String,System.String,System.String,System.String,Microsoft.CodeAnalysis.DiagnosticSeverity,System.Boolean,System.String,System.String,System.String[]); Analyzers should extend 'AbstractBuiltInCodeStyleDiagnosticAnalyzer' or 'AbstractCodeQualityDiagnosticAnalyzer' instead M:Microsoft.CodeAnalysis.DiagnosticDescriptor.#ctor(System.String,Microsoft.CodeAnalysis.LocalizableString,Microsoft.CodeAnalysis.LocalizableString,System.String,Microsoft.CodeAnalysis.DiagnosticSeverity,System.Boolean,Microsoft.CodeAnalysis.LocalizableString,System.String,System.String[]); Analyzers should extend 'AbstractBuiltInCodeStyleDiagnosticAnalyzer' or 'AbstractCodeQualityDiagnosticAnalyzer' instead T:System.ComponentModel.Composition.ExportAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.ExportMetadataAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.ImportAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.ImportManyAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.ImportMetadataConstraintAttribut; Use types from System.Composition instead T:System.ComponentModel.Composition.ImportingConstructorAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.MetadataAttributeAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.OnImportsSatisfiedAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.PartMetadataAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.PartNotDiscoverableAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.SharedAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.SharingBoundaryAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.Convention.AttributedModelProvider; Use types from System.Composition instead
P:Microsoft.CodeAnalysis.Project.LanguageServices; Use 'GetExtendedLanguageServices' instead M:Microsoft.CodeAnalysis.Host.HostWorkspaceServices.GetLanguageServices(System.String); Use 'GetExtendedLanguageServices' or directly get the language service by invoking 'GetLanguageService' or 'GetRequiredLanguageService' T:Microsoft.CodeAnalysis.Options.OptionSet; 'OptionSet' is not available in CodeStyle layer. Add a using/Imports statement defining 'OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions' when preprocessor variable 'CODE_STYLE' is defined T:Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption`1; Use 'Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption2' instead T:Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions; Use 'Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions2' instead T:Microsoft.CodeAnalysis.Options.OptionKey; Use 'Microsoft.CodeAnalysis.Options.OptionKey2' instead T:Microsoft.CodeAnalysis.CodeStyle.NotificationOption; Use 'Microsoft.CodeAnalysis.CodeStyle.NotificationOption2' instead M:Microsoft.CodeAnalysis.DiagnosticDescriptor.#ctor(System.String,System.String,System.String,System.String,Microsoft.CodeAnalysis.DiagnosticSeverity,System.Boolean,System.String,System.String,System.String[]); Analyzers should extend 'AbstractBuiltInCodeStyleDiagnosticAnalyzer' or 'AbstractCodeQualityDiagnosticAnalyzer' instead M:Microsoft.CodeAnalysis.DiagnosticDescriptor.#ctor(System.String,Microsoft.CodeAnalysis.LocalizableString,Microsoft.CodeAnalysis.LocalizableString,System.String,Microsoft.CodeAnalysis.DiagnosticSeverity,System.Boolean,Microsoft.CodeAnalysis.LocalizableString,System.String,System.String[]); Analyzers should extend 'AbstractBuiltInCodeStyleDiagnosticAnalyzer' or 'AbstractCodeQualityDiagnosticAnalyzer' instead T:System.ComponentModel.Composition.ExportAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.ExportMetadataAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.ImportAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.ImportManyAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.ImportMetadataConstraintAttribut; Use types from System.Composition instead T:System.ComponentModel.Composition.ImportingConstructorAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.MetadataAttributeAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.OnImportsSatisfiedAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.PartMetadataAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.PartNotDiscoverableAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.SharedAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.SharingBoundaryAttribute; Use types from System.Composition instead T:System.ComponentModel.Composition.Convention.AttributedModelProvider; Use types from System.Composition instead
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Analyzers/Core/Analyzers/UseThrowExpression/AbstractUseThrowExpressionDiagnosticAnalyzer.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.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.UseThrowExpression { /// <summary> /// Looks for patterns of the form: /// <code> /// if (a == null) { /// throw SomeException(); /// } /// /// x = a; /// </code> /// /// and offers to change it to /// /// <code> /// x = a ?? throw SomeException(); /// </code> /// /// Note: this analyzer can be updated to run on VB once VB supports 'throw' /// expressions as well. /// </summary> internal abstract class AbstractUseThrowExpressionDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private readonly Option2<CodeStyleOption2<bool>> _preferThrowExpressionOption; protected AbstractUseThrowExpressionDiagnosticAnalyzer(Option2<CodeStyleOption2<bool>> preferThrowExpressionOption, string language) : base(IDEDiagnosticIds.UseThrowExpressionDiagnosticId, EnforceOnBuildValues.UseThrowExpression, preferThrowExpressionOption, language, new LocalizableResourceString(nameof(AnalyzersResources.Use_throw_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _preferThrowExpressionOption = preferThrowExpressionOption; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected abstract bool IsSupported(Compilation compilation); protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(startContext => { if (!IsSupported(startContext.Compilation)) { return; } var expressionTypeOpt = startContext.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1"); startContext.RegisterOperationAction(operationContext => AnalyzeOperation(operationContext, expressionTypeOpt), OperationKind.Throw); }); } private void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol expressionTypeOpt) { var cancellationToken = context.CancellationToken; var throwOperation = (IThrowOperation)context.Operation; var throwStatementSyntax = throwOperation.Syntax; var semanticModel = context.Operation.SemanticModel; var ifOperation = GetContainingIfOperation( semanticModel, throwOperation, cancellationToken); // This throw statement isn't parented by an if-statement. Nothing to // do here. if (ifOperation == null) { return; } if (ifOperation.WhenFalse != null) { // Can't offer this if the 'if-statement' has an 'else-clause'. return; } var option = context.GetOption(_preferThrowExpressionOption); if (!option.Value) { return; } if (IsInExpressionTree(semanticModel, throwStatementSyntax, expressionTypeOpt, cancellationToken)) { return; } if (ifOperation.Parent is not IBlockOperation containingBlock) { return; } if (!TryDecomposeIfCondition(ifOperation, out var localOrParameter)) { return; } if (!TryFindAssignmentExpression(containingBlock, ifOperation, localOrParameter, out var expressionStatement, out var assignmentExpression)) { return; } if (!localOrParameter.GetSymbolType().CanAddNullCheck()) { return; } // We found an assignment using this local/parameter. Now, just make sure there // were no intervening accesses between the check and the assignment. if (ValueIsAccessed( semanticModel, ifOperation, containingBlock, localOrParameter, expressionStatement, assignmentExpression)) { return; } // Ok, there were no intervening writes or accesses. This check+assignment can be simplified. var allLocations = ImmutableArray.Create( ifOperation.Syntax.GetLocation(), throwOperation.Exception.Syntax.GetLocation(), assignmentExpression.Value.Syntax.GetLocation()); context.ReportDiagnostic( DiagnosticHelper.Create(Descriptor, throwStatementSyntax.GetLocation(), option.Notification.Severity, additionalLocations: allLocations, properties: null)); } private static bool ValueIsAccessed(SemanticModel semanticModel, IConditionalOperation ifOperation, IBlockOperation containingBlock, ISymbol localOrParameter, IExpressionStatementOperation expressionStatement, IAssignmentOperation assignmentExpression) { var statements = containingBlock.Operations; var ifOperationIndex = statements.IndexOf(ifOperation); var expressionStatementIndex = statements.IndexOf(expressionStatement); if (expressionStatementIndex > ifOperationIndex + 1) { // There are intermediary statements between the check and the assignment. // Make sure they don't try to access the local. var dataFlow = semanticModel.AnalyzeDataFlow( statements[ifOperationIndex + 1].Syntax, statements[expressionStatementIndex - 1].Syntax); if (dataFlow.ReadInside.Contains(localOrParameter) || dataFlow.WrittenInside.Contains(localOrParameter)) { return true; } } // Also, have to make sure there is no read/write of the local/parameter on the left // of the assignment. For example: map[val.Id] = val; var exprDataFlow = semanticModel.AnalyzeDataFlow(assignmentExpression.Target.Syntax); return exprDataFlow.ReadInside.Contains(localOrParameter) || exprDataFlow.WrittenInside.Contains(localOrParameter); } protected abstract bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol expressionTypeOpt, CancellationToken cancellationToken); private bool TryFindAssignmentExpression( IBlockOperation containingBlock, IConditionalOperation ifOperation, ISymbol localOrParameter, out IExpressionStatementOperation expressionStatement, out IAssignmentOperation assignmentExpression) { var ifOperationIndex = containingBlock.Operations.IndexOf(ifOperation); // walk forward until we find an assignment of this local/parameter into // something else. for (var i = ifOperationIndex + 1; i < containingBlock.Operations.Length; i++) { expressionStatement = containingBlock.Operations[i] as IExpressionStatementOperation; if (expressionStatement == null) { continue; } assignmentExpression = expressionStatement.Operation as IAssignmentOperation; if (assignmentExpression == null) { continue; } if (!TryGetLocalOrParameterSymbol(assignmentExpression.Value, out var assignmentValue)) { continue; } if (!Equals(localOrParameter, assignmentValue)) { continue; } return true; } expressionStatement = null; assignmentExpression = null; return false; } private bool TryDecomposeIfCondition( IConditionalOperation ifStatement, out ISymbol localOrParameter) { localOrParameter = null; var condition = ifStatement.Condition; if (condition is not IBinaryOperation binaryOperator) { return false; } if (binaryOperator.OperatorKind != BinaryOperatorKind.Equals) { return false; } if (IsNull(binaryOperator.LeftOperand)) { return TryGetLocalOrParameterSymbol( binaryOperator.RightOperand, out localOrParameter); } if (IsNull(binaryOperator.RightOperand)) { return TryGetLocalOrParameterSymbol( binaryOperator.LeftOperand, out localOrParameter); } return false; } private bool TryGetLocalOrParameterSymbol( IOperation operation, out ISymbol localOrParameter) { if (operation is IConversionOperation conversion && conversion.IsImplicit) { return TryGetLocalOrParameterSymbol(conversion.Operand, out localOrParameter); } else if (operation is ILocalReferenceOperation localReference) { localOrParameter = localReference.Local; return true; } else if (operation is IParameterReferenceOperation parameterReference) { localOrParameter = parameterReference.Parameter; return true; } localOrParameter = null; return false; } private static bool IsNull(IOperation operation) { return operation.ConstantValue.HasValue && operation.ConstantValue.Value == null; } private static IConditionalOperation GetContainingIfOperation( SemanticModel semanticModel, IThrowOperation throwOperation, CancellationToken cancellationToken) { var throwStatement = throwOperation.Syntax; var containingOperation = semanticModel.GetOperation(throwStatement.Parent, cancellationToken); if (containingOperation is IBlockOperation block) { if (block.Operations.Length != 1) { // If we are in a block, then the block must only contain // the throw statement. return null; } // C# may have an intermediary block between the throw-statement // and the if-statement. Walk up one operation higher in that case. containingOperation = semanticModel.GetOperation(throwStatement.Parent.Parent, cancellationToken); } if (containingOperation is IConditionalOperation conditionalOperation) { return conditionalOperation; } 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.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.UseThrowExpression { /// <summary> /// Looks for patterns of the form: /// <code> /// if (a == null) { /// throw SomeException(); /// } /// /// x = a; /// </code> /// /// and offers to change it to /// /// <code> /// x = a ?? throw SomeException(); /// </code> /// /// Note: this analyzer can be updated to run on VB once VB supports 'throw' /// expressions as well. /// </summary> internal abstract class AbstractUseThrowExpressionDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private readonly Option2<CodeStyleOption2<bool>> _preferThrowExpressionOption; protected AbstractUseThrowExpressionDiagnosticAnalyzer(Option2<CodeStyleOption2<bool>> preferThrowExpressionOption, string language) : base(IDEDiagnosticIds.UseThrowExpressionDiagnosticId, EnforceOnBuildValues.UseThrowExpression, preferThrowExpressionOption, language, new LocalizableResourceString(nameof(AnalyzersResources.Use_throw_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _preferThrowExpressionOption = preferThrowExpressionOption; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected abstract bool IsSupported(Compilation compilation); protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(startContext => { if (!IsSupported(startContext.Compilation)) { return; } var expressionTypeOpt = startContext.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1"); startContext.RegisterOperationAction(operationContext => AnalyzeOperation(operationContext, expressionTypeOpt), OperationKind.Throw); }); } private void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol expressionTypeOpt) { var cancellationToken = context.CancellationToken; var throwOperation = (IThrowOperation)context.Operation; var throwStatementSyntax = throwOperation.Syntax; var semanticModel = context.Operation.SemanticModel; var ifOperation = GetContainingIfOperation( semanticModel, throwOperation, cancellationToken); // This throw statement isn't parented by an if-statement. Nothing to // do here. if (ifOperation == null) { return; } if (ifOperation.WhenFalse != null) { // Can't offer this if the 'if-statement' has an 'else-clause'. return; } var option = context.GetOption(_preferThrowExpressionOption); if (!option.Value) { return; } if (IsInExpressionTree(semanticModel, throwStatementSyntax, expressionTypeOpt, cancellationToken)) { return; } if (ifOperation.Parent is not IBlockOperation containingBlock) { return; } if (!TryDecomposeIfCondition(ifOperation, out var localOrParameter)) { return; } if (!TryFindAssignmentExpression(containingBlock, ifOperation, localOrParameter, out var expressionStatement, out var assignmentExpression)) { return; } if (!localOrParameter.GetSymbolType().CanAddNullCheck()) { return; } // We found an assignment using this local/parameter. Now, just make sure there // were no intervening accesses between the check and the assignment. if (ValueIsAccessed( semanticModel, ifOperation, containingBlock, localOrParameter, expressionStatement, assignmentExpression)) { return; } // Ok, there were no intervening writes or accesses. This check+assignment can be simplified. var allLocations = ImmutableArray.Create( ifOperation.Syntax.GetLocation(), throwOperation.Exception.Syntax.GetLocation(), assignmentExpression.Value.Syntax.GetLocation()); context.ReportDiagnostic( DiagnosticHelper.Create(Descriptor, throwStatementSyntax.GetLocation(), option.Notification.Severity, additionalLocations: allLocations, properties: null)); } private static bool ValueIsAccessed(SemanticModel semanticModel, IConditionalOperation ifOperation, IBlockOperation containingBlock, ISymbol localOrParameter, IExpressionStatementOperation expressionStatement, IAssignmentOperation assignmentExpression) { var statements = containingBlock.Operations; var ifOperationIndex = statements.IndexOf(ifOperation); var expressionStatementIndex = statements.IndexOf(expressionStatement); if (expressionStatementIndex > ifOperationIndex + 1) { // There are intermediary statements between the check and the assignment. // Make sure they don't try to access the local. var dataFlow = semanticModel.AnalyzeDataFlow( statements[ifOperationIndex + 1].Syntax, statements[expressionStatementIndex - 1].Syntax); if (dataFlow.ReadInside.Contains(localOrParameter) || dataFlow.WrittenInside.Contains(localOrParameter)) { return true; } } // Also, have to make sure there is no read/write of the local/parameter on the left // of the assignment. For example: map[val.Id] = val; var exprDataFlow = semanticModel.AnalyzeDataFlow(assignmentExpression.Target.Syntax); return exprDataFlow.ReadInside.Contains(localOrParameter) || exprDataFlow.WrittenInside.Contains(localOrParameter); } protected abstract bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol expressionTypeOpt, CancellationToken cancellationToken); private bool TryFindAssignmentExpression( IBlockOperation containingBlock, IConditionalOperation ifOperation, ISymbol localOrParameter, out IExpressionStatementOperation expressionStatement, out IAssignmentOperation assignmentExpression) { var ifOperationIndex = containingBlock.Operations.IndexOf(ifOperation); // walk forward until we find an assignment of this local/parameter into // something else. for (var i = ifOperationIndex + 1; i < containingBlock.Operations.Length; i++) { expressionStatement = containingBlock.Operations[i] as IExpressionStatementOperation; if (expressionStatement == null) { continue; } assignmentExpression = expressionStatement.Operation as IAssignmentOperation; if (assignmentExpression == null) { continue; } if (!TryGetLocalOrParameterSymbol(assignmentExpression.Value, out var assignmentValue)) { continue; } if (!Equals(localOrParameter, assignmentValue)) { continue; } return true; } expressionStatement = null; assignmentExpression = null; return false; } private bool TryDecomposeIfCondition( IConditionalOperation ifStatement, out ISymbol localOrParameter) { localOrParameter = null; var condition = ifStatement.Condition; if (condition is not IBinaryOperation binaryOperator) { return false; } if (binaryOperator.OperatorKind != BinaryOperatorKind.Equals) { return false; } if (IsNull(binaryOperator.LeftOperand)) { return TryGetLocalOrParameterSymbol( binaryOperator.RightOperand, out localOrParameter); } if (IsNull(binaryOperator.RightOperand)) { return TryGetLocalOrParameterSymbol( binaryOperator.LeftOperand, out localOrParameter); } return false; } private bool TryGetLocalOrParameterSymbol( IOperation operation, out ISymbol localOrParameter) { if (operation is IConversionOperation conversion && conversion.IsImplicit) { return TryGetLocalOrParameterSymbol(conversion.Operand, out localOrParameter); } else if (operation is ILocalReferenceOperation localReference) { localOrParameter = localReference.Local; return true; } else if (operation is IParameterReferenceOperation parameterReference) { localOrParameter = parameterReference.Parameter; return true; } localOrParameter = null; return false; } private static bool IsNull(IOperation operation) { return operation.ConstantValue.HasValue && operation.ConstantValue.Value == null; } private static IConditionalOperation GetContainingIfOperation( SemanticModel semanticModel, IThrowOperation throwOperation, CancellationToken cancellationToken) { var throwStatement = throwOperation.Syntax; var containingOperation = semanticModel.GetOperation(throwStatement.Parent, cancellationToken); if (containingOperation is IBlockOperation block) { if (block.Operations.Length != 1) { // If we are in a block, then the block must only contain // the throw statement. return null; } // C# may have an intermediary block between the throw-statement // and the if-statement. Walk up one operation higher in that case. containingOperation = semanticModel.GetOperation(throwStatement.Parent.Parent, cancellationToken); } if (containingOperation is IConditionalOperation conditionalOperation) { return conditionalOperation; } return null; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Test/Resources/Core/SymbolsTests/DifferByCase/Consumer.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. // csc /target:library Consumer.cs /r:TypeAndNamespaceDifferByCase.dll public class TC1 : SomeName.Dummy { } public class TC2 : somEnamE { } public class TC3 : somEnamE1 { } public class TC4 : SomeName1 { } public class TC5 : somEnamE2.OtherName { } public class TC6 : SomeName2.OtherName { } public class TC7 : NestingClass.somEnamE3 { } public class TC8 : NestingClass.SomeName3 { }
// 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. // csc /target:library Consumer.cs /r:TypeAndNamespaceDifferByCase.dll public class TC1 : SomeName.Dummy { } public class TC2 : somEnamE { } public class TC3 : somEnamE1 { } public class TC4 : SomeName1 { } public class TC5 : somEnamE2.OtherName { } public class TC6 : SomeName2.OtherName { } public class TC7 : NestingClass.somEnamE3 { } public class TC8 : NestingClass.SomeName3 { }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo.Node.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.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SymbolTreeInfo { private const int RootNodeParentIndex = -1; /// <summary> /// <see cref="BuilderNode"/>s are produced when initially creating our indices. /// They store Names of symbols and the index of their parent symbol. When we /// produce the final <see cref="SymbolTreeInfo"/> though we will then convert /// these to <see cref="Node"/>s. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] private struct BuilderNode { public static readonly BuilderNode RootNode = new("", RootNodeParentIndex, default); public readonly string Name; public readonly int ParentIndex; public readonly MultiDictionary<MetadataNode, ParameterTypeInfo>.ValueSet ParameterTypeInfos; public BuilderNode(string name, int parentIndex, MultiDictionary<MetadataNode, ParameterTypeInfo>.ValueSet parameterTypeInfos = default) { Name = name; ParentIndex = parentIndex; ParameterTypeInfos = parameterTypeInfos; } public bool IsRoot => ParentIndex == RootNodeParentIndex; private string GetDebuggerDisplay() => Name + ", " + ParentIndex; } [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] private struct Node { /// <summary> /// The Name of this Node. /// </summary> public readonly string Name; /// <summary> /// Index in <see cref="_nodes"/> of the parent Node of this Node. /// Value will be <see cref="RootNodeParentIndex"/> if this is the /// Node corresponding to the root symbol. /// </summary> public readonly int ParentIndex; public Node(string name, int parentIndex) { Name = name; ParentIndex = parentIndex; } public bool IsRoot => ParentIndex == RootNodeParentIndex; public void AssertEquivalentTo(Node node) { Debug.Assert(node.Name == this.Name); Debug.Assert(node.ParentIndex == this.ParentIndex); } private string GetDebuggerDisplay() => Name + ", " + ParentIndex; } private readonly struct ParameterTypeInfo { /// <summary> /// This is the type name of the parameter when <see cref="IsComplexType"/> is false. /// For array types, this is just the elemtent type name. /// e.g. `int` for `int[][,]` /// </summary> public readonly string Name; /// <summary> /// Indicate if the type of parameter is any kind of array. /// This is relevant for both simple and complex types. For example: /// - array of simple type like int[], int[][], int[][,], etc. are all ultimately represented as "int[]" in index. /// - array of complex type like T[], T[][], etc are all represented as "[]" in index, /// in contrast to just "" for non-array types. /// </summary> public readonly bool IsArray; /// <summary> /// Similar to <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>, we divide extension methods into simple /// and complex categories for filtering purpose. Whether a method is simple is determined based on if we /// can determine it's receiver type easily with a pure text matching. For complex methods, we will need to /// rely on symbol to decide if it's feasible. /// /// Simple types include: /// - Primitive types /// - Types which is not a generic method parameter /// - By reference type of any types above /// - Array types with element of any types above /// </summary> public readonly bool IsComplexType; public ParameterTypeInfo(string name, bool isComplex, bool isArray) { Name = name; IsComplexType = isComplex; IsArray = isArray; } } public readonly struct ExtensionMethodInfo { /// <summary> /// Name of the extension method. /// This can be used to retrive corresponding symbols via <see cref="INamespaceOrTypeSymbol.GetMembers(string)"/> /// </summary> public readonly string Name; /// <summary> /// Fully qualified name for the type that contains this extension method. /// </summary> public readonly string FullyQualifiedContainerName; public ExtensionMethodInfo(string fullyQualifiedContainerName, string name) { FullyQualifiedContainerName = fullyQualifiedContainerName; Name = name; } } private sealed class ParameterTypeInfoProvider : ISignatureTypeProvider<ParameterTypeInfo, object> { public static readonly ParameterTypeInfoProvider Instance = new(); private static ParameterTypeInfo ComplexInfo => new(string.Empty, isComplex: true, isArray: false); public ParameterTypeInfo GetPrimitiveType(PrimitiveTypeCode typeCode) => new(typeCode.ToString(), isComplex: false, isArray: false); public ParameterTypeInfo GetGenericInstantiation(ParameterTypeInfo genericType, ImmutableArray<ParameterTypeInfo> typeArguments) => genericType.IsComplexType ? ComplexInfo : new ParameterTypeInfo(genericType.Name, isComplex: false, isArray: false); public ParameterTypeInfo GetByReferenceType(ParameterTypeInfo elementType) => elementType; public ParameterTypeInfo GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) { var type = reader.GetTypeDefinition(handle); var name = reader.GetString(type.Name); return new ParameterTypeInfo(name, isComplex: false, isArray: false); } public ParameterTypeInfo GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) { var type = reader.GetTypeReference(handle); var name = reader.GetString(type.Name); return new ParameterTypeInfo(name, isComplex: false, isArray: false); } public ParameterTypeInfo GetTypeFromSpecification(MetadataReader reader, object genericContext, TypeSpecificationHandle handle, byte rawTypeKind) { var sigReader = reader.GetBlobReader(reader.GetTypeSpecification(handle).Signature); return new SignatureDecoder<ParameterTypeInfo, object>(Instance, reader, genericContext).DecodeType(ref sigReader); } public ParameterTypeInfo GetArrayType(ParameterTypeInfo elementType, ArrayShape shape) => GetArrayTypeInfo(elementType); public ParameterTypeInfo GetSZArrayType(ParameterTypeInfo elementType) => GetArrayTypeInfo(elementType); private static ParameterTypeInfo GetArrayTypeInfo(ParameterTypeInfo elementType) => elementType.IsComplexType ? new ParameterTypeInfo(string.Empty, isComplex: true, isArray: true) : new ParameterTypeInfo(elementType.Name, isComplex: false, isArray: true); public ParameterTypeInfo GetFunctionPointerType(MethodSignature<ParameterTypeInfo> signature) => ComplexInfo; public ParameterTypeInfo GetGenericMethodParameter(object genericContext, int index) => ComplexInfo; public ParameterTypeInfo GetGenericTypeParameter(object genericContext, int index) => ComplexInfo; public ParameterTypeInfo GetModifiedType(ParameterTypeInfo modifier, ParameterTypeInfo unmodifiedType, bool isRequired) => ComplexInfo; public ParameterTypeInfo GetPinnedType(ParameterTypeInfo elementType) => ComplexInfo; public ParameterTypeInfo GetPointerType(ParameterTypeInfo elementType) => ComplexInfo; } } }
// 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.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SymbolTreeInfo { private const int RootNodeParentIndex = -1; /// <summary> /// <see cref="BuilderNode"/>s are produced when initially creating our indices. /// They store Names of symbols and the index of their parent symbol. When we /// produce the final <see cref="SymbolTreeInfo"/> though we will then convert /// these to <see cref="Node"/>s. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] private struct BuilderNode { public static readonly BuilderNode RootNode = new("", RootNodeParentIndex, default); public readonly string Name; public readonly int ParentIndex; public readonly MultiDictionary<MetadataNode, ParameterTypeInfo>.ValueSet ParameterTypeInfos; public BuilderNode(string name, int parentIndex, MultiDictionary<MetadataNode, ParameterTypeInfo>.ValueSet parameterTypeInfos = default) { Name = name; ParentIndex = parentIndex; ParameterTypeInfos = parameterTypeInfos; } public bool IsRoot => ParentIndex == RootNodeParentIndex; private string GetDebuggerDisplay() => Name + ", " + ParentIndex; } [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] private struct Node { /// <summary> /// The Name of this Node. /// </summary> public readonly string Name; /// <summary> /// Index in <see cref="_nodes"/> of the parent Node of this Node. /// Value will be <see cref="RootNodeParentIndex"/> if this is the /// Node corresponding to the root symbol. /// </summary> public readonly int ParentIndex; public Node(string name, int parentIndex) { Name = name; ParentIndex = parentIndex; } public bool IsRoot => ParentIndex == RootNodeParentIndex; public void AssertEquivalentTo(Node node) { Debug.Assert(node.Name == this.Name); Debug.Assert(node.ParentIndex == this.ParentIndex); } private string GetDebuggerDisplay() => Name + ", " + ParentIndex; } private readonly struct ParameterTypeInfo { /// <summary> /// This is the type name of the parameter when <see cref="IsComplexType"/> is false. /// For array types, this is just the elemtent type name. /// e.g. `int` for `int[][,]` /// </summary> public readonly string Name; /// <summary> /// Indicate if the type of parameter is any kind of array. /// This is relevant for both simple and complex types. For example: /// - array of simple type like int[], int[][], int[][,], etc. are all ultimately represented as "int[]" in index. /// - array of complex type like T[], T[][], etc are all represented as "[]" in index, /// in contrast to just "" for non-array types. /// </summary> public readonly bool IsArray; /// <summary> /// Similar to <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>, we divide extension methods into simple /// and complex categories for filtering purpose. Whether a method is simple is determined based on if we /// can determine it's receiver type easily with a pure text matching. For complex methods, we will need to /// rely on symbol to decide if it's feasible. /// /// Simple types include: /// - Primitive types /// - Types which is not a generic method parameter /// - By reference type of any types above /// - Array types with element of any types above /// </summary> public readonly bool IsComplexType; public ParameterTypeInfo(string name, bool isComplex, bool isArray) { Name = name; IsComplexType = isComplex; IsArray = isArray; } } public readonly struct ExtensionMethodInfo { /// <summary> /// Name of the extension method. /// This can be used to retrive corresponding symbols via <see cref="INamespaceOrTypeSymbol.GetMembers(string)"/> /// </summary> public readonly string Name; /// <summary> /// Fully qualified name for the type that contains this extension method. /// </summary> public readonly string FullyQualifiedContainerName; public ExtensionMethodInfo(string fullyQualifiedContainerName, string name) { FullyQualifiedContainerName = fullyQualifiedContainerName; Name = name; } } private sealed class ParameterTypeInfoProvider : ISignatureTypeProvider<ParameterTypeInfo, object> { public static readonly ParameterTypeInfoProvider Instance = new(); private static ParameterTypeInfo ComplexInfo => new(string.Empty, isComplex: true, isArray: false); public ParameterTypeInfo GetPrimitiveType(PrimitiveTypeCode typeCode) => new(typeCode.ToString(), isComplex: false, isArray: false); public ParameterTypeInfo GetGenericInstantiation(ParameterTypeInfo genericType, ImmutableArray<ParameterTypeInfo> typeArguments) => genericType.IsComplexType ? ComplexInfo : new ParameterTypeInfo(genericType.Name, isComplex: false, isArray: false); public ParameterTypeInfo GetByReferenceType(ParameterTypeInfo elementType) => elementType; public ParameterTypeInfo GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) { var type = reader.GetTypeDefinition(handle); var name = reader.GetString(type.Name); return new ParameterTypeInfo(name, isComplex: false, isArray: false); } public ParameterTypeInfo GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) { var type = reader.GetTypeReference(handle); var name = reader.GetString(type.Name); return new ParameterTypeInfo(name, isComplex: false, isArray: false); } public ParameterTypeInfo GetTypeFromSpecification(MetadataReader reader, object genericContext, TypeSpecificationHandle handle, byte rawTypeKind) { var sigReader = reader.GetBlobReader(reader.GetTypeSpecification(handle).Signature); return new SignatureDecoder<ParameterTypeInfo, object>(Instance, reader, genericContext).DecodeType(ref sigReader); } public ParameterTypeInfo GetArrayType(ParameterTypeInfo elementType, ArrayShape shape) => GetArrayTypeInfo(elementType); public ParameterTypeInfo GetSZArrayType(ParameterTypeInfo elementType) => GetArrayTypeInfo(elementType); private static ParameterTypeInfo GetArrayTypeInfo(ParameterTypeInfo elementType) => elementType.IsComplexType ? new ParameterTypeInfo(string.Empty, isComplex: true, isArray: true) : new ParameterTypeInfo(elementType.Name, isComplex: false, isArray: true); public ParameterTypeInfo GetFunctionPointerType(MethodSignature<ParameterTypeInfo> signature) => ComplexInfo; public ParameterTypeInfo GetGenericMethodParameter(object genericContext, int index) => ComplexInfo; public ParameterTypeInfo GetGenericTypeParameter(object genericContext, int index) => ComplexInfo; public ParameterTypeInfo GetModifiedType(ParameterTypeInfo modifier, ParameterTypeInfo unmodifiedType, bool isRequired) => ComplexInfo; public ParameterTypeInfo GetPinnedType(ParameterTypeInfo elementType) => ComplexInfo; public ParameterTypeInfo GetPointerType(ParameterTypeInfo elementType) => ComplexInfo; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Workspaces/Core/MSBuild/PublicAPI.Shipped.txt
Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.AssociateFileExtensionWithLanguage(string projectFileExtension, string language) -> void Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadMetadataForReferencedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadMetadataForReferencedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadProjectInfoAsync(string projectFilePath, Microsoft.CodeAnalysis.MSBuild.ProjectMap projectMap = null, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, Microsoft.Build.Framework.ILogger msbuildLogger = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ProjectInfo>> Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadSolutionInfoAsync(string solutionFilePath, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, Microsoft.Build.Framework.ILogger msbuildLogger = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SolutionInfo> Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.MSBuildProjectLoader(Microsoft.CodeAnalysis.Workspace workspace, System.Collections.Immutable.ImmutableDictionary<string, string> properties = null) -> void Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.Properties.get -> System.Collections.Immutable.ImmutableDictionary<string, string> Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.SkipUnrecognizedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.SkipUnrecognizedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.AssociateFileExtensionWithLanguage(string projectFileExtension, string language) -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.CloseSolution() -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Diagnostics.get -> System.Collections.Immutable.ImmutableList<Microsoft.CodeAnalysis.WorkspaceDiagnostic> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.LoadMetadataForReferencedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.LoadMetadataForReferencedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenProjectAsync(string projectFilePath, Microsoft.Build.Framework.ILogger msbuildLogger, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Project> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenProjectAsync(string projectFilePath, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Project> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenSolutionAsync(string solutionFilePath, Microsoft.Build.Framework.ILogger msbuildLogger, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenSolutionAsync(string solutionFilePath, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Properties.get -> System.Collections.Immutable.ImmutableDictionary<string, string> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.SkipUnrecognizedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.SkipUnrecognizedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation.Build = 1 -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation.Evaluate = 0 -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation.Resolve = 2 -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.ElapsedTime.get -> System.TimeSpan Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.FilePath.get -> string Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.Operation.get -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.ProjectLoadProgress() -> void Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.TargetFramework.get -> string Microsoft.CodeAnalysis.MSBuild.ProjectMap Microsoft.CodeAnalysis.MSBuild.ProjectMap.Add(Microsoft.CodeAnalysis.Project project) -> void override Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.CanApplyChange(Microsoft.CodeAnalysis.ApplyChangesKind feature) -> bool override Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.TryApplyChanges(Microsoft.CodeAnalysis.Solution newSolution) -> bool static Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices.DefaultAssemblies.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Assembly> static Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices.DefaultServices.get -> Microsoft.CodeAnalysis.Host.Mef.MefHostServices static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create() -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(Microsoft.CodeAnalysis.Host.HostServices hostServices) -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(System.Collections.Generic.IDictionary<string, string> properties) -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(System.Collections.Generic.IDictionary<string, string> properties, Microsoft.CodeAnalysis.Host.HostServices hostServices) -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.ProjectMap.Create() -> Microsoft.CodeAnalysis.MSBuild.ProjectMap static Microsoft.CodeAnalysis.MSBuild.ProjectMap.Create(Microsoft.CodeAnalysis.Solution solution) -> Microsoft.CodeAnalysis.MSBuild.ProjectMap
Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.AssociateFileExtensionWithLanguage(string projectFileExtension, string language) -> void Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadMetadataForReferencedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadMetadataForReferencedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadProjectInfoAsync(string projectFilePath, Microsoft.CodeAnalysis.MSBuild.ProjectMap projectMap = null, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, Microsoft.Build.Framework.ILogger msbuildLogger = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ProjectInfo>> Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadSolutionInfoAsync(string solutionFilePath, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, Microsoft.Build.Framework.ILogger msbuildLogger = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SolutionInfo> Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.MSBuildProjectLoader(Microsoft.CodeAnalysis.Workspace workspace, System.Collections.Immutable.ImmutableDictionary<string, string> properties = null) -> void Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.Properties.get -> System.Collections.Immutable.ImmutableDictionary<string, string> Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.SkipUnrecognizedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.SkipUnrecognizedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.AssociateFileExtensionWithLanguage(string projectFileExtension, string language) -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.CloseSolution() -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Diagnostics.get -> System.Collections.Immutable.ImmutableList<Microsoft.CodeAnalysis.WorkspaceDiagnostic> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.LoadMetadataForReferencedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.LoadMetadataForReferencedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenProjectAsync(string projectFilePath, Microsoft.Build.Framework.ILogger msbuildLogger, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Project> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenProjectAsync(string projectFilePath, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Project> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenSolutionAsync(string solutionFilePath, Microsoft.Build.Framework.ILogger msbuildLogger, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenSolutionAsync(string solutionFilePath, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Properties.get -> System.Collections.Immutable.ImmutableDictionary<string, string> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.SkipUnrecognizedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.SkipUnrecognizedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation.Build = 1 -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation.Evaluate = 0 -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation.Resolve = 2 -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.ElapsedTime.get -> System.TimeSpan Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.FilePath.get -> string Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.Operation.get -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.ProjectLoadProgress() -> void Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.TargetFramework.get -> string Microsoft.CodeAnalysis.MSBuild.ProjectMap Microsoft.CodeAnalysis.MSBuild.ProjectMap.Add(Microsoft.CodeAnalysis.Project project) -> void override Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.CanApplyChange(Microsoft.CodeAnalysis.ApplyChangesKind feature) -> bool override Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.TryApplyChanges(Microsoft.CodeAnalysis.Solution newSolution) -> bool static Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices.DefaultAssemblies.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Assembly> static Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices.DefaultServices.get -> Microsoft.CodeAnalysis.Host.Mef.MefHostServices static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create() -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(Microsoft.CodeAnalysis.Host.HostServices hostServices) -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(System.Collections.Generic.IDictionary<string, string> properties) -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(System.Collections.Generic.IDictionary<string, string> properties, Microsoft.CodeAnalysis.Host.HostServices hostServices) -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.ProjectMap.Create() -> Microsoft.CodeAnalysis.MSBuild.ProjectMap static Microsoft.CodeAnalysis.MSBuild.ProjectMap.Create(Microsoft.CodeAnalysis.Solution solution) -> Microsoft.CodeAnalysis.MSBuild.ProjectMap
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/CSharp/Portable/CSharpFileSystemExtensions.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.IO; using System.Threading; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp { public static class CSharpFileSystemExtensions { /// <summary> /// Emit the IL for the compilation into the specified stream. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="outputPath">Path of the file to which the PE image will be written.</param> /// <param name="pdbPath">Path of the file to which the compilation's debug info will be written. /// Also embedded in the output file. Null to forego PDB generation. /// </param> /// <param name="xmlDocumentationPath">Path of the file to which the compilation's XML documentation will be written. Null to forego XML generation.</param> /// <param name="win32ResourcesPath">Path of the file from which the compilation's Win32 resources will be read (in RES format). /// Null to indicate that there are none.</param> /// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param> /// <param name="cancellationToken">To cancel the emit process.</param> /// <exception cref="ArgumentNullException">Compilation or path is null.</exception> /// <exception cref="ArgumentException">Path is empty or invalid.</exception> /// <exception cref="IOException">An error occurred while reading or writing a file.</exception> public static EmitResult Emit( this CSharpCompilation compilation, string outputPath, string? pdbPath = null, string? xmlDocumentationPath = null, string? win32ResourcesPath = null, IEnumerable<ResourceDescription>? manifestResources = null, CancellationToken cancellationToken = default) { return FileSystemExtensions.Emit(compilation, outputPath, pdbPath, xmlDocumentationPath, win32ResourcesPath, manifestResources, 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. using System; using System.Collections.Generic; using System.IO; using System.Threading; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp { public static class CSharpFileSystemExtensions { /// <summary> /// Emit the IL for the compilation into the specified stream. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="outputPath">Path of the file to which the PE image will be written.</param> /// <param name="pdbPath">Path of the file to which the compilation's debug info will be written. /// Also embedded in the output file. Null to forego PDB generation. /// </param> /// <param name="xmlDocumentationPath">Path of the file to which the compilation's XML documentation will be written. Null to forego XML generation.</param> /// <param name="win32ResourcesPath">Path of the file from which the compilation's Win32 resources will be read (in RES format). /// Null to indicate that there are none.</param> /// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param> /// <param name="cancellationToken">To cancel the emit process.</param> /// <exception cref="ArgumentNullException">Compilation or path is null.</exception> /// <exception cref="ArgumentException">Path is empty or invalid.</exception> /// <exception cref="IOException">An error occurred while reading or writing a file.</exception> public static EmitResult Emit( this CSharpCompilation compilation, string outputPath, string? pdbPath = null, string? xmlDocumentationPath = null, string? win32ResourcesPath = null, IEnumerable<ResourceDescription>? manifestResources = null, CancellationToken cancellationToken = default) { return FileSystemExtensions.Emit(compilation, outputPath, pdbPath, xmlDocumentationPath, win32ResourcesPath, manifestResources, cancellationToken); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/Core/Portable/Completion/ArgumentContext.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; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Provides context information for argument completion. /// </summary> internal sealed class ArgumentContext { public ArgumentContext( ArgumentProvider provider, SemanticModel semanticModel, int position, IParameterSymbol parameter, string? previousValue, CancellationToken cancellationToken) { Provider = provider ?? throw new ArgumentNullException(nameof(provider)); SemanticModel = semanticModel ?? throw new ArgumentNullException(nameof(semanticModel)); Position = position; Parameter = parameter ?? throw new ArgumentNullException(nameof(parameter)); PreviousValue = previousValue; CancellationToken = cancellationToken; } internal ArgumentProvider Provider { get; } /// <summary> /// Gets the semantic model where argument completion is requested. /// </summary> public SemanticModel SemanticModel { get; } /// <summary> /// Gets the position within <see cref="SemanticModel"/> where argument completion is requested. /// </summary> public int Position { get; } /// <summary> /// Gets the symbol for the parameter for which an argument value is requested. /// </summary> public IParameterSymbol Parameter { get; } /// <summary> /// Gets the previously-provided argument value for this parameter. /// </summary> /// <value> /// The existing text of the argument value, if the argument is already in code; otherwise, /// <see langword="null"/> when requesting a new argument value. /// </value> public string? PreviousValue { get; } /// <summary> /// Gets a cancellation token that argument providers may observe. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Gets or sets the default argument value. /// </summary> /// <remarks> /// If this value is not set, the argument completion session will insert a language-specific default value for /// the argument. /// </remarks> public string? DefaultValue { get; set; } } }
// 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; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Provides context information for argument completion. /// </summary> internal sealed class ArgumentContext { public ArgumentContext( ArgumentProvider provider, SemanticModel semanticModel, int position, IParameterSymbol parameter, string? previousValue, CancellationToken cancellationToken) { Provider = provider ?? throw new ArgumentNullException(nameof(provider)); SemanticModel = semanticModel ?? throw new ArgumentNullException(nameof(semanticModel)); Position = position; Parameter = parameter ?? throw new ArgumentNullException(nameof(parameter)); PreviousValue = previousValue; CancellationToken = cancellationToken; } internal ArgumentProvider Provider { get; } /// <summary> /// Gets the semantic model where argument completion is requested. /// </summary> public SemanticModel SemanticModel { get; } /// <summary> /// Gets the position within <see cref="SemanticModel"/> where argument completion is requested. /// </summary> public int Position { get; } /// <summary> /// Gets the symbol for the parameter for which an argument value is requested. /// </summary> public IParameterSymbol Parameter { get; } /// <summary> /// Gets the previously-provided argument value for this parameter. /// </summary> /// <value> /// The existing text of the argument value, if the argument is already in code; otherwise, /// <see langword="null"/> when requesting a new argument value. /// </value> public string? PreviousValue { get; } /// <summary> /// Gets a cancellation token that argument providers may observe. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Gets or sets the default argument value. /// </summary> /// <remarks> /// If this value is not set, the argument completion session will insert a language-specific default value for /// the argument. /// </remarks> public string? DefaultValue { get; set; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/CSharp/Portable/Binder/LocalScopeBinder.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalScopeBinder : Binder { private ImmutableArray<LocalSymbol> _locals; private ImmutableArray<LocalFunctionSymbol> _localFunctions; private ImmutableArray<LabelSymbol> _labels; private readonly uint _localScopeDepth; internal LocalScopeBinder(Binder next) : this(next, next.Flags) { } internal LocalScopeBinder(Binder next, BinderFlags flags) : base(next, flags) { var parentDepth = next.LocalScopeDepth; if (parentDepth != Binder.TopLevelScope) { _localScopeDepth = parentDepth + 1; } else { //NOTE: TopLevel is special. //For our purpose parameters and top level locals are on that level. var parentScope = next; while (parentScope != null) { if (parentScope is InMethodBinder || parentScope is WithLambdaParametersBinder) { _localScopeDepth = Binder.TopLevelScope; break; } if (parentScope is LocalScopeBinder) { _localScopeDepth = Binder.TopLevelScope + 1; break; } parentScope = parentScope.Next; Debug.Assert(parentScope != null); } } } internal sealed override ImmutableArray<LocalSymbol> Locals { get { if (_locals.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _locals, BuildLocals(), default(ImmutableArray<LocalSymbol>)); } return _locals; } } protected virtual ImmutableArray<LocalSymbol> BuildLocals() { return ImmutableArray<LocalSymbol>.Empty; } internal sealed override ImmutableArray<LocalFunctionSymbol> LocalFunctions { get { if (_localFunctions.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _localFunctions, BuildLocalFunctions(), default(ImmutableArray<LocalFunctionSymbol>)); } return _localFunctions; } } protected virtual ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { return ImmutableArray<LocalFunctionSymbol>.Empty; } internal sealed override ImmutableArray<LabelSymbol> Labels { get { if (_labels.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _labels, BuildLabels(), default(ImmutableArray<LabelSymbol>)); } return _labels; } } protected virtual ImmutableArray<LabelSymbol> BuildLabels() { return ImmutableArray<LabelSymbol>.Empty; } private SmallDictionary<string, LocalSymbol> _lazyLocalsMap; private SmallDictionary<string, LocalSymbol> LocalsMap { get { if (_lazyLocalsMap == null && this.Locals.Length > 0) { _lazyLocalsMap = BuildMap(this.Locals); } return _lazyLocalsMap; } } private SmallDictionary<string, LocalFunctionSymbol> _lazyLocalFunctionsMap; private SmallDictionary<string, LocalFunctionSymbol> LocalFunctionsMap { get { if (_lazyLocalFunctionsMap == null && this.LocalFunctions.Length > 0) { _lazyLocalFunctionsMap = BuildMap(this.LocalFunctions); } return _lazyLocalFunctionsMap; } } private SmallDictionary<string, LabelSymbol> _lazyLabelsMap; private SmallDictionary<string, LabelSymbol> LabelsMap { get { if (_lazyLabelsMap == null && this.Labels.Length > 0) { _lazyLabelsMap = BuildMap(this.Labels); } return _lazyLabelsMap; } } private static SmallDictionary<string, TSymbol> BuildMap<TSymbol>(ImmutableArray<TSymbol> array) where TSymbol : Symbol { Debug.Assert(array.Length > 0); var map = new SmallDictionary<string, TSymbol>(); // NOTE: in a rare case of having two symbols with same name the one closer to the array's start wins. for (int i = array.Length - 1; i >= 0; i--) { var symbol = array[i]; map[symbol.Name] = symbol; } return map; } protected ImmutableArray<LocalSymbol> BuildLocals(SyntaxList<StatementSyntax> statements, Binder enclosingBinder) { #if DEBUG Binder currentBinder = enclosingBinder; while (true) { if (this == currentBinder) { break; } currentBinder = currentBinder.Next; } #endif ArrayBuilder<LocalSymbol> locals = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var statement in statements) { BuildLocals(enclosingBinder, statement, locals); } return locals.ToImmutableAndFree(); } internal void BuildLocals(Binder enclosingBinder, StatementSyntax statement, ArrayBuilder<LocalSymbol> locals) { var innerStatement = statement; // drill into any LabeledStatements -- atomic LabelStatements have been bound into // wrapped LabeledStatements by this point while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } switch (innerStatement.Kind()) { case SyntaxKind.LocalDeclarationStatement: { Binder localDeclarationBinder = enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder; var decl = (LocalDeclarationStatementSyntax)innerStatement; decl.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var expression in rankSpecifier.Sizes) { if (expression.Kind() != SyntaxKind.OmittedArraySizeExpression) { ExpressionVariableFinder.FindExpressionVariables(args.localScopeBinder, args.locals, expression, args.localDeclarationBinder); } } }, (localScopeBinder: this, locals: locals, localDeclarationBinder: localDeclarationBinder)); LocalDeclarationKind kind; if (decl.IsConst) { kind = LocalDeclarationKind.Constant; } else if (decl.UsingKeyword != default(SyntaxToken)) { kind = LocalDeclarationKind.UsingVariable; } else { kind = LocalDeclarationKind.RegularVariable; } foreach (var vdecl in decl.Declaration.Variables) { var localSymbol = MakeLocal(decl.Declaration, vdecl, kind, localDeclarationBinder); locals.Add(localSymbol); // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionVariableFinder.FindExpressionVariables(this, locals, vdecl, localDeclarationBinder); } } break; case SyntaxKind.ExpressionStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.GotoCaseStatement: ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder); break; case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)innerStatement; ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(switchStatement.Expression) ?? enclosingBinder); break; case SyntaxKind.LockStatement: Binder statementBinder = enclosingBinder.GetBinder(innerStatement); Debug.Assert(statementBinder != null); // Lock always has a binder. ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, statementBinder); break; default: // no other statement introduces local variables into the enclosing scope break; } } protected ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions(SyntaxList<StatementSyntax> statements) { ArrayBuilder<LocalFunctionSymbol> locals = null; foreach (var statement in statements) { BuildLocalFunctions(statement, ref locals); } return locals?.ToImmutableAndFree() ?? ImmutableArray<LocalFunctionSymbol>.Empty; } internal void BuildLocalFunctions(StatementSyntax statement, ref ArrayBuilder<LocalFunctionSymbol> locals) { var innerStatement = statement; // drill into any LabeledStatements -- atomic LabelStatements have been bound into // wrapped LabeledStatements by this point while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } if (innerStatement.Kind() == SyntaxKind.LocalFunctionStatement) { var decl = (LocalFunctionStatementSyntax)innerStatement; if (locals == null) { locals = ArrayBuilder<LocalFunctionSymbol>.GetInstance(); } var localSymbol = MakeLocalFunction(decl); locals.Add(localSymbol); } } protected SourceLocalSymbol MakeLocal(VariableDeclarationSyntax declaration, VariableDeclaratorSyntax declarator, LocalDeclarationKind kind, Binder initializerBinderOpt = null) { return SourceLocalSymbol.MakeLocal( this.ContainingMemberOrLambda, this, true, declaration.Type, declarator.Identifier, kind, declarator.Initializer, initializerBinderOpt); } protected LocalFunctionSymbol MakeLocalFunction(LocalFunctionStatementSyntax declaration) { return new LocalFunctionSymbol( this, this.ContainingMemberOrLambda, declaration); } protected void BuildLabels(SyntaxList<StatementSyntax> statements, ref ArrayBuilder<LabelSymbol> labels) { var containingMethod = (MethodSymbol)this.ContainingMemberOrLambda; foreach (var statement in statements) { BuildLabels(containingMethod, statement, ref labels); } } internal static void BuildLabels(MethodSymbol containingMethod, StatementSyntax statement, ref ArrayBuilder<LabelSymbol> labels) { while (statement.Kind() == SyntaxKind.LabeledStatement) { var labeledStatement = (LabeledStatementSyntax)statement; if (labels == null) { labels = ArrayBuilder<LabelSymbol>.GetInstance(); } var labelSymbol = new SourceLabelSymbol(containingMethod, labeledStatement.Identifier); labels.Add(labelSymbol); statement = labeledStatement.Statement; } } /// <summary> /// Call this when you are sure there is a local declaration on this token. Returns the local. /// </summary> protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { LocalSymbol result = null; if (LocalsMap != null && LocalsMap.TryGetValue(nameToken.ValueText, out result)) { if (result.IdentifierToken == nameToken) return (SourceLocalSymbol)result; // in error cases we might have more than one declaration of the same name in the same scope foreach (var local in this.Locals) { if (local.IdentifierToken == nameToken) { return (SourceLocalSymbol)local; } } } return base.LookupLocal(nameToken); } protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) { LocalFunctionSymbol result = null; if (LocalFunctionsMap != null && LocalFunctionsMap.TryGetValue(nameToken.ValueText, out result)) { if (result.NameToken == nameToken) return result; // in error cases we might have more than one declaration of the same name in the same scope foreach (var local in this.LocalFunctions) { if (local.NameToken == nameToken) { return local; } } } return base.LookupLocalFunction(nameToken); } internal override uint LocalScopeDepth => _localScopeDepth; internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(options.AreValid()); Debug.Assert(result.IsClear); if ((options & LookupOptions.LabelsOnly) != 0) { var labelsMap = this.LabelsMap; if (labelsMap != null) { LabelSymbol labelSymbol; if (labelsMap.TryGetValue(name, out labelSymbol)) { result.MergeEqual(LookupResult.Good(labelSymbol)); } } return; } var localsMap = this.LocalsMap; if (localsMap != null && (options & LookupOptions.NamespaceAliasesOnly) == 0) { LocalSymbol localSymbol; if (localsMap.TryGetValue(name, out localSymbol)) { result.MergeEqual(originalBinder.CheckViability(localSymbol, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved)); } } var localFunctionsMap = this.LocalFunctionsMap; if (localFunctionsMap != null && options.CanConsiderLocals()) { LocalFunctionSymbol localSymbol; if (localFunctionsMap.TryGetValue(name, out localSymbol)) { result.MergeEqual(originalBinder.CheckViability(localSymbol, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved)); } } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { Debug.Assert(options.AreValid()); if ((options & LookupOptions.LabelsOnly) != 0) { if (this.LabelsMap != null) { foreach (var label in this.LabelsMap) { result.AddSymbol(label.Value, label.Key, 0); } } } if (options.CanConsiderLocals()) { if (this.LocalsMap != null) { foreach (var local in this.LocalsMap) { if (originalBinder.CanAddLookupSymbolInfo(local.Value, options, result, null)) { result.AddSymbol(local.Value, local.Key, 0); } } } if (this.LocalFunctionsMap != null) { foreach (var local in this.LocalFunctionsMap) { if (originalBinder.CanAddLookupSymbolInfo(local.Value, options, result, null)) { result.AddSymbol(local.Value, local.Key, 0); } } } } } private bool ReportConflictWithLocal(Symbol local, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics) { // Quirk of the way we represent lambda parameters. SymbolKind newSymbolKind = (object)newSymbol == null ? SymbolKind.Parameter : newSymbol.Kind; if (newSymbolKind == SymbolKind.ErrorType) return true; var declaredInThisScope = false; declaredInThisScope |= newSymbolKind == SymbolKind.Local && this.Locals.Contains((LocalSymbol)newSymbol); declaredInThisScope |= newSymbolKind == SymbolKind.Method && this.LocalFunctions.Contains((LocalFunctionSymbol)newSymbol); if (declaredInThisScope && newLocation.SourceSpan.Start >= local.Locations[0].SourceSpan.Start) { // A local variable or function named '{0}' is already defined in this scope diagnostics.Add(ErrorCode.ERR_LocalDuplicate, newLocation, name); return true; } switch (newSymbolKind) { case SymbolKind.Local: case SymbolKind.Parameter: case SymbolKind.Method: case SymbolKind.TypeParameter: // A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name); return true; case SymbolKind.RangeVariable: // The range variable '{0}' conflicts with a previous declaration of '{0}' diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name); return true; } Debug.Assert(false, "what else can be declared inside a local scope?"); diagnostics.Add(ErrorCode.ERR_InternalError, newLocation); return false; } internal virtual bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics) { LocalSymbol existingLocal = null; LocalFunctionSymbol existingLocalFunction = null; var localsMap = this.LocalsMap; var localFunctionsMap = this.LocalFunctionsMap; // TODO: Handle case where 'name' exists in both localsMap and localFunctionsMap. Right now locals are preferred over local functions. if ((localsMap != null && localsMap.TryGetValue(name, out existingLocal)) || (localFunctionsMap != null && localFunctionsMap.TryGetValue(name, out existingLocalFunction))) { var existingSymbol = (Symbol)existingLocal ?? existingLocalFunction; if (symbol == existingSymbol) { // reference to same symbol, by far the most common case. return false; } return ReportConflictWithLocal(existingSymbol, symbol, name, location, diagnostics); } return false; } } }
// 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalScopeBinder : Binder { private ImmutableArray<LocalSymbol> _locals; private ImmutableArray<LocalFunctionSymbol> _localFunctions; private ImmutableArray<LabelSymbol> _labels; private readonly uint _localScopeDepth; internal LocalScopeBinder(Binder next) : this(next, next.Flags) { } internal LocalScopeBinder(Binder next, BinderFlags flags) : base(next, flags) { var parentDepth = next.LocalScopeDepth; if (parentDepth != Binder.TopLevelScope) { _localScopeDepth = parentDepth + 1; } else { //NOTE: TopLevel is special. //For our purpose parameters and top level locals are on that level. var parentScope = next; while (parentScope != null) { if (parentScope is InMethodBinder || parentScope is WithLambdaParametersBinder) { _localScopeDepth = Binder.TopLevelScope; break; } if (parentScope is LocalScopeBinder) { _localScopeDepth = Binder.TopLevelScope + 1; break; } parentScope = parentScope.Next; Debug.Assert(parentScope != null); } } } internal sealed override ImmutableArray<LocalSymbol> Locals { get { if (_locals.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _locals, BuildLocals(), default(ImmutableArray<LocalSymbol>)); } return _locals; } } protected virtual ImmutableArray<LocalSymbol> BuildLocals() { return ImmutableArray<LocalSymbol>.Empty; } internal sealed override ImmutableArray<LocalFunctionSymbol> LocalFunctions { get { if (_localFunctions.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _localFunctions, BuildLocalFunctions(), default(ImmutableArray<LocalFunctionSymbol>)); } return _localFunctions; } } protected virtual ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { return ImmutableArray<LocalFunctionSymbol>.Empty; } internal sealed override ImmutableArray<LabelSymbol> Labels { get { if (_labels.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _labels, BuildLabels(), default(ImmutableArray<LabelSymbol>)); } return _labels; } } protected virtual ImmutableArray<LabelSymbol> BuildLabels() { return ImmutableArray<LabelSymbol>.Empty; } private SmallDictionary<string, LocalSymbol> _lazyLocalsMap; private SmallDictionary<string, LocalSymbol> LocalsMap { get { if (_lazyLocalsMap == null && this.Locals.Length > 0) { _lazyLocalsMap = BuildMap(this.Locals); } return _lazyLocalsMap; } } private SmallDictionary<string, LocalFunctionSymbol> _lazyLocalFunctionsMap; private SmallDictionary<string, LocalFunctionSymbol> LocalFunctionsMap { get { if (_lazyLocalFunctionsMap == null && this.LocalFunctions.Length > 0) { _lazyLocalFunctionsMap = BuildMap(this.LocalFunctions); } return _lazyLocalFunctionsMap; } } private SmallDictionary<string, LabelSymbol> _lazyLabelsMap; private SmallDictionary<string, LabelSymbol> LabelsMap { get { if (_lazyLabelsMap == null && this.Labels.Length > 0) { _lazyLabelsMap = BuildMap(this.Labels); } return _lazyLabelsMap; } } private static SmallDictionary<string, TSymbol> BuildMap<TSymbol>(ImmutableArray<TSymbol> array) where TSymbol : Symbol { Debug.Assert(array.Length > 0); var map = new SmallDictionary<string, TSymbol>(); // NOTE: in a rare case of having two symbols with same name the one closer to the array's start wins. for (int i = array.Length - 1; i >= 0; i--) { var symbol = array[i]; map[symbol.Name] = symbol; } return map; } protected ImmutableArray<LocalSymbol> BuildLocals(SyntaxList<StatementSyntax> statements, Binder enclosingBinder) { #if DEBUG Binder currentBinder = enclosingBinder; while (true) { if (this == currentBinder) { break; } currentBinder = currentBinder.Next; } #endif ArrayBuilder<LocalSymbol> locals = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var statement in statements) { BuildLocals(enclosingBinder, statement, locals); } return locals.ToImmutableAndFree(); } internal void BuildLocals(Binder enclosingBinder, StatementSyntax statement, ArrayBuilder<LocalSymbol> locals) { var innerStatement = statement; // drill into any LabeledStatements -- atomic LabelStatements have been bound into // wrapped LabeledStatements by this point while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } switch (innerStatement.Kind()) { case SyntaxKind.LocalDeclarationStatement: { Binder localDeclarationBinder = enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder; var decl = (LocalDeclarationStatementSyntax)innerStatement; decl.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var expression in rankSpecifier.Sizes) { if (expression.Kind() != SyntaxKind.OmittedArraySizeExpression) { ExpressionVariableFinder.FindExpressionVariables(args.localScopeBinder, args.locals, expression, args.localDeclarationBinder); } } }, (localScopeBinder: this, locals: locals, localDeclarationBinder: localDeclarationBinder)); LocalDeclarationKind kind; if (decl.IsConst) { kind = LocalDeclarationKind.Constant; } else if (decl.UsingKeyword != default(SyntaxToken)) { kind = LocalDeclarationKind.UsingVariable; } else { kind = LocalDeclarationKind.RegularVariable; } foreach (var vdecl in decl.Declaration.Variables) { var localSymbol = MakeLocal(decl.Declaration, vdecl, kind, localDeclarationBinder); locals.Add(localSymbol); // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionVariableFinder.FindExpressionVariables(this, locals, vdecl, localDeclarationBinder); } } break; case SyntaxKind.ExpressionStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.GotoCaseStatement: ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder); break; case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)innerStatement; ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(switchStatement.Expression) ?? enclosingBinder); break; case SyntaxKind.LockStatement: Binder statementBinder = enclosingBinder.GetBinder(innerStatement); Debug.Assert(statementBinder != null); // Lock always has a binder. ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, statementBinder); break; default: // no other statement introduces local variables into the enclosing scope break; } } protected ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions(SyntaxList<StatementSyntax> statements) { ArrayBuilder<LocalFunctionSymbol> locals = null; foreach (var statement in statements) { BuildLocalFunctions(statement, ref locals); } return locals?.ToImmutableAndFree() ?? ImmutableArray<LocalFunctionSymbol>.Empty; } internal void BuildLocalFunctions(StatementSyntax statement, ref ArrayBuilder<LocalFunctionSymbol> locals) { var innerStatement = statement; // drill into any LabeledStatements -- atomic LabelStatements have been bound into // wrapped LabeledStatements by this point while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } if (innerStatement.Kind() == SyntaxKind.LocalFunctionStatement) { var decl = (LocalFunctionStatementSyntax)innerStatement; if (locals == null) { locals = ArrayBuilder<LocalFunctionSymbol>.GetInstance(); } var localSymbol = MakeLocalFunction(decl); locals.Add(localSymbol); } } protected SourceLocalSymbol MakeLocal(VariableDeclarationSyntax declaration, VariableDeclaratorSyntax declarator, LocalDeclarationKind kind, Binder initializerBinderOpt = null) { return SourceLocalSymbol.MakeLocal( this.ContainingMemberOrLambda, this, true, declaration.Type, declarator.Identifier, kind, declarator.Initializer, initializerBinderOpt); } protected LocalFunctionSymbol MakeLocalFunction(LocalFunctionStatementSyntax declaration) { return new LocalFunctionSymbol( this, this.ContainingMemberOrLambda, declaration); } protected void BuildLabels(SyntaxList<StatementSyntax> statements, ref ArrayBuilder<LabelSymbol> labels) { var containingMethod = (MethodSymbol)this.ContainingMemberOrLambda; foreach (var statement in statements) { BuildLabels(containingMethod, statement, ref labels); } } internal static void BuildLabels(MethodSymbol containingMethod, StatementSyntax statement, ref ArrayBuilder<LabelSymbol> labels) { while (statement.Kind() == SyntaxKind.LabeledStatement) { var labeledStatement = (LabeledStatementSyntax)statement; if (labels == null) { labels = ArrayBuilder<LabelSymbol>.GetInstance(); } var labelSymbol = new SourceLabelSymbol(containingMethod, labeledStatement.Identifier); labels.Add(labelSymbol); statement = labeledStatement.Statement; } } /// <summary> /// Call this when you are sure there is a local declaration on this token. Returns the local. /// </summary> protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { LocalSymbol result = null; if (LocalsMap != null && LocalsMap.TryGetValue(nameToken.ValueText, out result)) { if (result.IdentifierToken == nameToken) return (SourceLocalSymbol)result; // in error cases we might have more than one declaration of the same name in the same scope foreach (var local in this.Locals) { if (local.IdentifierToken == nameToken) { return (SourceLocalSymbol)local; } } } return base.LookupLocal(nameToken); } protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) { LocalFunctionSymbol result = null; if (LocalFunctionsMap != null && LocalFunctionsMap.TryGetValue(nameToken.ValueText, out result)) { if (result.NameToken == nameToken) return result; // in error cases we might have more than one declaration of the same name in the same scope foreach (var local in this.LocalFunctions) { if (local.NameToken == nameToken) { return local; } } } return base.LookupLocalFunction(nameToken); } internal override uint LocalScopeDepth => _localScopeDepth; internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(options.AreValid()); Debug.Assert(result.IsClear); if ((options & LookupOptions.LabelsOnly) != 0) { var labelsMap = this.LabelsMap; if (labelsMap != null) { LabelSymbol labelSymbol; if (labelsMap.TryGetValue(name, out labelSymbol)) { result.MergeEqual(LookupResult.Good(labelSymbol)); } } return; } var localsMap = this.LocalsMap; if (localsMap != null && (options & LookupOptions.NamespaceAliasesOnly) == 0) { LocalSymbol localSymbol; if (localsMap.TryGetValue(name, out localSymbol)) { result.MergeEqual(originalBinder.CheckViability(localSymbol, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved)); } } var localFunctionsMap = this.LocalFunctionsMap; if (localFunctionsMap != null && options.CanConsiderLocals()) { LocalFunctionSymbol localSymbol; if (localFunctionsMap.TryGetValue(name, out localSymbol)) { result.MergeEqual(originalBinder.CheckViability(localSymbol, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved)); } } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { Debug.Assert(options.AreValid()); if ((options & LookupOptions.LabelsOnly) != 0) { if (this.LabelsMap != null) { foreach (var label in this.LabelsMap) { result.AddSymbol(label.Value, label.Key, 0); } } } if (options.CanConsiderLocals()) { if (this.LocalsMap != null) { foreach (var local in this.LocalsMap) { if (originalBinder.CanAddLookupSymbolInfo(local.Value, options, result, null)) { result.AddSymbol(local.Value, local.Key, 0); } } } if (this.LocalFunctionsMap != null) { foreach (var local in this.LocalFunctionsMap) { if (originalBinder.CanAddLookupSymbolInfo(local.Value, options, result, null)) { result.AddSymbol(local.Value, local.Key, 0); } } } } } private bool ReportConflictWithLocal(Symbol local, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics) { // Quirk of the way we represent lambda parameters. SymbolKind newSymbolKind = (object)newSymbol == null ? SymbolKind.Parameter : newSymbol.Kind; if (newSymbolKind == SymbolKind.ErrorType) return true; var declaredInThisScope = false; declaredInThisScope |= newSymbolKind == SymbolKind.Local && this.Locals.Contains((LocalSymbol)newSymbol); declaredInThisScope |= newSymbolKind == SymbolKind.Method && this.LocalFunctions.Contains((LocalFunctionSymbol)newSymbol); if (declaredInThisScope && newLocation.SourceSpan.Start >= local.Locations[0].SourceSpan.Start) { // A local variable or function named '{0}' is already defined in this scope diagnostics.Add(ErrorCode.ERR_LocalDuplicate, newLocation, name); return true; } switch (newSymbolKind) { case SymbolKind.Local: case SymbolKind.Parameter: case SymbolKind.Method: case SymbolKind.TypeParameter: // A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name); return true; case SymbolKind.RangeVariable: // The range variable '{0}' conflicts with a previous declaration of '{0}' diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name); return true; } Debug.Assert(false, "what else can be declared inside a local scope?"); diagnostics.Add(ErrorCode.ERR_InternalError, newLocation); return false; } internal virtual bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics) { LocalSymbol existingLocal = null; LocalFunctionSymbol existingLocalFunction = null; var localsMap = this.LocalsMap; var localFunctionsMap = this.LocalFunctionsMap; // TODO: Handle case where 'name' exists in both localsMap and localFunctionsMap. Right now locals are preferred over local functions. if ((localsMap != null && localsMap.TryGetValue(name, out existingLocal)) || (localFunctionsMap != null && localFunctionsMap.TryGetValue(name, out existingLocalFunction))) { var existingSymbol = (Symbol)existingLocal ?? existingLocalFunction; if (symbol == existingSymbol) { // reference to same symbol, by far the most common case. return false; } return ReportConflictWithLocal(existingSymbol, symbol, name, location, diagnostics); } return false; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/NamespaceGlobalTests.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 Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class NamespaceGlobalTests ' Global is the root of all namespace even set root namespace of compilation <Fact> Public Sub RootNSForGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace NS1 Public Class Class1 'Global.NS1.Class1 End Class End Namespace Class C1 'Global.C1 End Class </file> </compilation>) Dim opt = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("RootNS") Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp2"> <file name="a.vb"> Namespace Global.Global.ns1 Class C2 End Class End Namespace Namespace [Global].ns1 Class C1 End Class End Namespace Class C1 'RootNS.C1 End Class </file> </compilation>, options:=opt) ' While the root namespace is empty it means Global is the container CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Class1", "NS1.Class1") CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "C1") ' While set the root namespace of compilation to "RootNS" ,'RootNS' is inside global namespace Dim globalNS2 = compilation2.GlobalNamespace Dim rootNS2 = DirectCast(globalNS2.GetMembers("RootNS").Single(), NamespaceSymbol) CompilationUtils.VerifyIsGlobal(rootNS2.ContainingSymbol) ' The container of C1 Dim typeSymbol2C1 = CompilationUtils.VerifyGlobalNamespace(compilation2, "a.vb", "C1", "RootNS.Global.ns1.C1", "RootNS.C1") ' The container of C1 Dim symbolC2 = CompilationUtils.VerifyGlobalNamespace(compilation2, "a.vb", "C2", "[Global].ns1.C2") End Sub ' Empty Name Space is equal to Global while Root namespace is empty <Fact> Public Sub BC30179ERR_TypeConflict6_RootNSIsEmpty() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Class A End Class Namespace Global Class A 'invalid End Class End Namespace </file> </compilation>) ' While the root namespace is empty it means Global is the container Dim symbolA = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "A", {"A", "A"}, False) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors> BC30179: class 'A' and class 'A' conflict in namespace '&lt;Default&gt;'. Class A ~ </errors>) End Sub ' Set the root namespace of compilation to 'Global' <Fact> Public Sub RootNSIsGlobal() Dim opt = TestOptions.ReleaseDll.WithRootNamespace("Global") Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Class A End Class Namespace Global Class A Dim s As Global.Global.A Dim s1 As [Global].A Dim s2 As Global.A End Class End Namespace </file> </compilation>, options:=opt) ' While the root namespace is Global it means [Global] Dim globalNS = compilation1.SourceModule.GlobalNamespace Dim nsGlobal = CompilationUtils.VerifyIsGlobal(globalNS.GetMembers("Global").Single, False) Assert.Equal("[Global]", nsGlobal.ToDisplayString()) Dim symbolA = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "A", "[Global].A", "A") CompilationUtils.AssertNoErrors(compilation1) End Sub <WorkItem(527731, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527731")> <Fact> Public Sub GlobalInSourceVsGlobalInOptions() Dim source = <compilation name="comp1"> <file name="a.vb"> Namespace [Global] End Namespace </file> </compilation> Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(source) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("Global")) Dim globalNS1 = compilation1.SourceModule.GlobalNamespace.GetMembers().Single() Dim globalNS2 = compilation2.SourceModule.GlobalNamespace.GetMembers().Single() Assert.Equal("Global", globalNS1.Name) Assert.Equal("Global", globalNS2.Name) Assert.Single(compilation1.GlobalNamespace.GetMembers("Global").AsEnumerable()) Assert.Single(compilation2.GlobalNamespace.GetMembers("Global").AsEnumerable()) Assert.Empty(compilation1.GlobalNamespace.GetMembers("[Global]").AsEnumerable()) Assert.Empty(compilation2.GlobalNamespace.GetMembers("[Global]").AsEnumerable()) End Sub ' Global for Partial class <Fact> Public Sub PartialInGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Partial Class Class1 End Class </file> <file name="b.vb"> Namespace Global Public Class Class1 End Class End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Class1", {"Class1"}, False) CompilationUtils.VerifyGlobalNamespace(compilation1, "b.vb", "Class1", {"Class1"}, False) Dim symbolClass = compilation1.GlobalNamespace.GetMembers("Class1").Single() Assert.Equal(2, DirectCast(symbolClass, NamedTypeSymbol).Locations.Length) End Sub ' Using escaped names for Global <WorkItem(527731, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527731")> <Fact> Public Sub EscapedGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace [Global] Public Class Class1 End Class End Namespace Namespace Global Public Class Class1 'valid End Class End Namespace </file> </compilation>) Assert.Equal(1, compilation1.SourceModule.GlobalNamespace.GetMembers("Global").Length) Dim symbolClass = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Class1", {"Class1", "[Global].Class1"}, False) End Sub ' Global is Not Case sensitive <Fact> Public Sub BC30179ERR_TypeConflict6_CaseSenGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace GLOBAL Class C1 End Class End Namespace Namespace global Class C1 'invalid End Class End Namespace </file> </compilation>) Dim symbolClass = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", {"C1", "C1"}, False) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors> BC30179: class 'C1' and class 'C1' conflict in namespace '&lt;Default&gt;'. Class C1 'invalid ~~ </errors>) End Sub ' Global for Imports <Fact> Public Sub BC36001ERR_NoGlobalExpectedIdentifier_ImportsGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Imports Global.[global]'invalid Imports Global.goo'invalid Imports Global 'invalid Imports a = [Global] 'valid Namespace [global] End Namespace Namespace goo End Namespace </file> </compilation>) Dim GlobalNSMember = compilation1.SourceModule.GlobalNamespace.GetMembers() Assert.True(GlobalNSMember(0).ContainingNamespace.IsGlobalNamespace) Assert.True(GlobalNSMember(1).ContainingNamespace.IsGlobalNamespace) CompilationUtils.AssertTheseParseDiagnostics(compilation1, <errors> BC36001: 'Global' not allowed in this context; identifier expected. Imports Global.[global]'invalid ~~~~~~ BC36001: 'Global' not allowed in this context; identifier expected. Imports Global.goo'invalid ~~~~~~ BC36001: 'Global' not allowed in this context; identifier expected. Imports Global 'invalid ~~~~~~ </errors>) End Sub ' Global for Alias name <Fact> Public Sub BC36001ERR_NoGlobalExpectedIdentifier_ImportsAliasGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Imports Global = System 'invalid Imports Global.[Global] = System 'invalid Imports [Global] = System 'valid </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC36001: 'Global' not allowed in this context; identifier expected. Imports Global = System 'invalid ~~~~~~ BC36001: 'Global' not allowed in this context; identifier expected. Imports Global.[Global] = System 'invalid ~~~~~~ BC40056: Namespace or type specified in the Imports 'Global.Global' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports Global.[Global] = System 'invalid ~~~~~~~~~~~~~~~ </errors>) End Sub ' Global can't be used as type <WorkItem(527728, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527728")> <Fact> Public Sub BC30183ERR_InvalidUseOfKeyword_GlobalAsType() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Imports System Class C1(Of T As Global) End Class Class C2 Inherits Global End Class Structure [Global] End Structure Class Global End Class </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Global", {"[Global]", "[Global]", "C1(Of T As [Global])"}, False) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30182: Type expected. Class C1(Of T As Global) ~~~~~~ BC30182: Type expected. Inherits Global ~~~~~~ BC30179: structure '[Global]' and class 'Global' conflict in namespace '&lt;Default&gt;'. Structure [Global] ~~~~~~~~ BC30179: class 'Global' and structure 'Global' conflict in namespace '&lt;Default&gt;'. Class Global ~~~~~~ BC30183: Keyword is not valid as an identifier. Class Global ~~~~~~ </errors>) End Sub ' Global can't be used as identifier <WorkItem(527728, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527728")> <Fact> Public Sub BC30183ERR_InvalidUseOfKeyword_GlobalAsIdentifier() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Class Global(Of T As Class) End Class Class C1(Of Global As Class) End Class </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Global", "[Global](Of T As Class)", "C1(Of [Global] As Class)") CompilationUtils.AssertTheseParseDiagnostics(compilation1, <errors> BC30183: Keyword is not valid as an identifier. Class Global(Of T As Class) ~~~~~~ BC30183: Keyword is not valid as an identifier. Class C1(Of Global As Class) ~~~~~~ </errors>) End Sub ' Global can't be used as Access Modifier <Fact> Public Sub BC30035ERR_Syntax_AccessModifier() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Global Class C1(of T as class) End Class </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "C1(Of T As Class)") CompilationUtils.AssertTheseParseDiagnostics(compilation1, <errors> BC30188: Declaration expected. Global Class C1(of T as class) ~~~~~~ </errors>) End Sub ' Global namespace may not be nested in another namespace <WorkItem(539076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539076")> <Fact> Public Sub BC31544ERR_NestedGlobalNamespace_NestedGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Namespace Global ' invalid Public Class c1 End Class End Namespace End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1") Assert.Equal("[Global]", compilation1.SourceModule.GlobalNamespace.GetMembers().Single().ToDisplayString()) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors> BC31544: Global namespace may not be nested in another namespace. Namespace Global ' invalid ~~~~~~ </errors>) End Sub ' [Global] namespace could be nested in another namespace <Fact> Public Sub NestedEscapedGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Namespace [Global] ' valid Public Class C1 End Class End Namespace End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "[Global].C1") CompilationUtils.AssertNoDeclarationDiagnostics(compilation1) End Sub ' Global in Fully qualified names <Fact> Public Sub FullyQualifiedOfGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Imports [Global].ns1 Namespace Global.Global.ns1 Class C1 End Class End Namespace Namespace [Global].ns1 Class C1 End Class End Namespace </file> <file name="b.vb"> Imports NS1.Global'valid NS1.Global considered NS1.[Global] Namespace NS1 Namespace [Global] Public Class C2 End Class End Namespace End Namespace </file> <file name="c.vb"> Namespace ns1.Global 'valid considered NS1.[Global] Public Class C2 End Class End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", {"[Global].ns1.C1", "[Global].ns1.C1"}, False) CompilationUtils.VerifyGlobalNamespace(compilation1, "b.vb", "C2", "NS1.Global.C2") CompilationUtils.VerifyGlobalNamespace(compilation1, "c.vb", "C2", "NS1.Global.C2") CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30179: class 'C1' and class 'C1' conflict in namespace '[Global].ns1'. Class C1 ~~ BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'NS1' in 'b.vb'. Namespace ns1.Global 'valid considered NS1.[Global] ~~~ BC30179: class 'C2' and class 'C2' conflict in namespace 'NS1.Global'. Public Class C2 ~~ </errors>) End Sub ' Different types in global namespace <Fact> Public Sub DiffTypeInGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="comp1"> <file name="a.vb"> Namespace Global Class [Global] Class UserdefCls End Class Structure UserdefStruct End Structure End Class Module M1 End Module Enum E1 ONE End Enum End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "UserdefCls", "[Global].UserdefCls") CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "UserdefStruct", "[Global].UserdefStruct") CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "M1", "M1") CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "E1", "E1") CompilationUtils.AssertNoErrors(compilation1) End Sub ' Access different fields with different access modifiers in Global <Fact> Public Sub DiffAccessInGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Public Class C1 Private Class C2 End Class Friend Class C3 End Class End Class End Namespace </file> </compilation>) Dim symbolC1 = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "C1") Dim symbolC2 = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C2", "C1.C2") Dim symbolC3 = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C3", "C1.C3") Assert.Equal(Accessibility.Public, symbolC1(0).DeclaredAccessibility) Assert.Equal(Accessibility.Private, symbolC2(0).DeclaredAccessibility) Assert.Equal(Accessibility.Friend, symbolC3(0).DeclaredAccessibility) End Sub ' Global works on Compilation <WorkItem(539077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539077")> <Fact> Public Sub BC30554ERR_AmbiguousInUnnamedNamespace1_GlobalOnCompilation() Dim opt1 = TestOptions.ReleaseDll.WithRootNamespace("NS1") Dim opt2 = TestOptions.ReleaseDll.WithRootNamespace("NS2") Dim opt3 = TestOptions.ReleaseDll.WithRootNamespace("NS3") Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Public Class C1 Private Class C2 End Class Public Class C3 End Class End Class End Namespace </file> </compilation>, options:=opt1) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp2"> <file name="a.vb"> Namespace Global Public Class C1 Private Class C2 End Class Public Class C3 End Class End Class End Namespace </file> </compilation>, options:=opt2) Dim ref1 = New VisualBasicCompilationReference(compilation1) Dim ref2 = New VisualBasicCompilationReference(compilation2) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp3"> <file name="a.vb"> Namespace NS1 Structure S1 Dim A As Global.C1.C2 ' invalid Dim B As Global.C1.C3 ' invalid End Structure End Namespace </file> </compilation>, options:=opt3) compilation3 = compilation3.AddReferences(ref1, ref2) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C2", "C1.C2") CompilationUtils.VerifyGlobalNamespace(compilation2, "a.vb", "C3", "C1.C3") CompilationUtils.AssertTheseDiagnostics(compilation3, <errors> BC30554: 'C1' is ambiguous. Dim A As Global.C1.C2 ' invalid ~~~~~~~~~ BC30554: 'C1' is ambiguous. Dim B As Global.C1.C3 ' invalid ~~~~~~~~~ </errors>) End Sub ' Define customer namespace same as namespace of the .NET Framework in Global <Fact> Public Sub DefSystemNSInGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Namespace System Class C1 Dim A As System.Int32 ' valid End Class End Namespace End Namespace </file> </compilation>) Dim symbolC1 = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "System.C1") CompilationUtils.AssertNoErrors(compilation1) End Sub <Fact> <WorkItem(545787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545787")> Public Sub NestedGlobalNS() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NestedGlobalNS"> <file name="a.vb"> Imports System Namespace N Namespace Global.M Class X 'BIND:"Class X" End Class End Namespace End Namespace </file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim typeStatementSyntax = CompilationUtils.FindBindingText(Of TypeStatementSyntax)(compilation, "a.vb", 0) Dim cls = DirectCast(model.GetDeclaredSymbol(typeStatementSyntax), NamedTypeSymbol) Assert.Equal("N.Global.M.X", cls.ToDisplayString()) End Sub <Fact> Public Sub Bug529716() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace Global Class C End Class End Namespace Namespace Global.Ns1 Class D End Class End Namespace </file> </compilation>) Dim [global] = compilation1.SourceModule.GlobalNamespace Dim classC = [global].GetTypeMembers("C").Single() Dim ns1 = DirectCast([global].GetMembers("Ns1").Single(), NamespaceSymbol) Dim classD = ns1.GetTypeMembers("D").Single() Assert.False(ns1.IsImplicitlyDeclared) For Each ref In [global].DeclaringSyntaxReferences Dim node = ref.GetSyntax() Assert.Equal(SyntaxKind.CompilationUnit, node.Kind) Next ' Since we never return something other than CompilationUnit as a declaring syntax for a Global namespace, ' the following assert should succeed. Assert.True([global].IsImplicitlyDeclared) 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 Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class NamespaceGlobalTests ' Global is the root of all namespace even set root namespace of compilation <Fact> Public Sub RootNSForGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace NS1 Public Class Class1 'Global.NS1.Class1 End Class End Namespace Class C1 'Global.C1 End Class </file> </compilation>) Dim opt = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("RootNS") Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp2"> <file name="a.vb"> Namespace Global.Global.ns1 Class C2 End Class End Namespace Namespace [Global].ns1 Class C1 End Class End Namespace Class C1 'RootNS.C1 End Class </file> </compilation>, options:=opt) ' While the root namespace is empty it means Global is the container CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Class1", "NS1.Class1") CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "C1") ' While set the root namespace of compilation to "RootNS" ,'RootNS' is inside global namespace Dim globalNS2 = compilation2.GlobalNamespace Dim rootNS2 = DirectCast(globalNS2.GetMembers("RootNS").Single(), NamespaceSymbol) CompilationUtils.VerifyIsGlobal(rootNS2.ContainingSymbol) ' The container of C1 Dim typeSymbol2C1 = CompilationUtils.VerifyGlobalNamespace(compilation2, "a.vb", "C1", "RootNS.Global.ns1.C1", "RootNS.C1") ' The container of C1 Dim symbolC2 = CompilationUtils.VerifyGlobalNamespace(compilation2, "a.vb", "C2", "[Global].ns1.C2") End Sub ' Empty Name Space is equal to Global while Root namespace is empty <Fact> Public Sub BC30179ERR_TypeConflict6_RootNSIsEmpty() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Class A End Class Namespace Global Class A 'invalid End Class End Namespace </file> </compilation>) ' While the root namespace is empty it means Global is the container Dim symbolA = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "A", {"A", "A"}, False) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors> BC30179: class 'A' and class 'A' conflict in namespace '&lt;Default&gt;'. Class A ~ </errors>) End Sub ' Set the root namespace of compilation to 'Global' <Fact> Public Sub RootNSIsGlobal() Dim opt = TestOptions.ReleaseDll.WithRootNamespace("Global") Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Class A End Class Namespace Global Class A Dim s As Global.Global.A Dim s1 As [Global].A Dim s2 As Global.A End Class End Namespace </file> </compilation>, options:=opt) ' While the root namespace is Global it means [Global] Dim globalNS = compilation1.SourceModule.GlobalNamespace Dim nsGlobal = CompilationUtils.VerifyIsGlobal(globalNS.GetMembers("Global").Single, False) Assert.Equal("[Global]", nsGlobal.ToDisplayString()) Dim symbolA = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "A", "[Global].A", "A") CompilationUtils.AssertNoErrors(compilation1) End Sub <WorkItem(527731, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527731")> <Fact> Public Sub GlobalInSourceVsGlobalInOptions() Dim source = <compilation name="comp1"> <file name="a.vb"> Namespace [Global] End Namespace </file> </compilation> Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(source) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(source, options:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("Global")) Dim globalNS1 = compilation1.SourceModule.GlobalNamespace.GetMembers().Single() Dim globalNS2 = compilation2.SourceModule.GlobalNamespace.GetMembers().Single() Assert.Equal("Global", globalNS1.Name) Assert.Equal("Global", globalNS2.Name) Assert.Single(compilation1.GlobalNamespace.GetMembers("Global").AsEnumerable()) Assert.Single(compilation2.GlobalNamespace.GetMembers("Global").AsEnumerable()) Assert.Empty(compilation1.GlobalNamespace.GetMembers("[Global]").AsEnumerable()) Assert.Empty(compilation2.GlobalNamespace.GetMembers("[Global]").AsEnumerable()) End Sub ' Global for Partial class <Fact> Public Sub PartialInGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Partial Class Class1 End Class </file> <file name="b.vb"> Namespace Global Public Class Class1 End Class End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Class1", {"Class1"}, False) CompilationUtils.VerifyGlobalNamespace(compilation1, "b.vb", "Class1", {"Class1"}, False) Dim symbolClass = compilation1.GlobalNamespace.GetMembers("Class1").Single() Assert.Equal(2, DirectCast(symbolClass, NamedTypeSymbol).Locations.Length) End Sub ' Using escaped names for Global <WorkItem(527731, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527731")> <Fact> Public Sub EscapedGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace [Global] Public Class Class1 End Class End Namespace Namespace Global Public Class Class1 'valid End Class End Namespace </file> </compilation>) Assert.Equal(1, compilation1.SourceModule.GlobalNamespace.GetMembers("Global").Length) Dim symbolClass = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Class1", {"Class1", "[Global].Class1"}, False) End Sub ' Global is Not Case sensitive <Fact> Public Sub BC30179ERR_TypeConflict6_CaseSenGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace GLOBAL Class C1 End Class End Namespace Namespace global Class C1 'invalid End Class End Namespace </file> </compilation>) Dim symbolClass = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", {"C1", "C1"}, False) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors> BC30179: class 'C1' and class 'C1' conflict in namespace '&lt;Default&gt;'. Class C1 'invalid ~~ </errors>) End Sub ' Global for Imports <Fact> Public Sub BC36001ERR_NoGlobalExpectedIdentifier_ImportsGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Imports Global.[global]'invalid Imports Global.goo'invalid Imports Global 'invalid Imports a = [Global] 'valid Namespace [global] End Namespace Namespace goo End Namespace </file> </compilation>) Dim GlobalNSMember = compilation1.SourceModule.GlobalNamespace.GetMembers() Assert.True(GlobalNSMember(0).ContainingNamespace.IsGlobalNamespace) Assert.True(GlobalNSMember(1).ContainingNamespace.IsGlobalNamespace) CompilationUtils.AssertTheseParseDiagnostics(compilation1, <errors> BC36001: 'Global' not allowed in this context; identifier expected. Imports Global.[global]'invalid ~~~~~~ BC36001: 'Global' not allowed in this context; identifier expected. Imports Global.goo'invalid ~~~~~~ BC36001: 'Global' not allowed in this context; identifier expected. Imports Global 'invalid ~~~~~~ </errors>) End Sub ' Global for Alias name <Fact> Public Sub BC36001ERR_NoGlobalExpectedIdentifier_ImportsAliasGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Imports Global = System 'invalid Imports Global.[Global] = System 'invalid Imports [Global] = System 'valid </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC36001: 'Global' not allowed in this context; identifier expected. Imports Global = System 'invalid ~~~~~~ BC36001: 'Global' not allowed in this context; identifier expected. Imports Global.[Global] = System 'invalid ~~~~~~ BC40056: Namespace or type specified in the Imports 'Global.Global' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports Global.[Global] = System 'invalid ~~~~~~~~~~~~~~~ </errors>) End Sub ' Global can't be used as type <WorkItem(527728, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527728")> <Fact> Public Sub BC30183ERR_InvalidUseOfKeyword_GlobalAsType() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Imports System Class C1(Of T As Global) End Class Class C2 Inherits Global End Class Structure [Global] End Structure Class Global End Class </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Global", {"[Global]", "[Global]", "C1(Of T As [Global])"}, False) CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30182: Type expected. Class C1(Of T As Global) ~~~~~~ BC30182: Type expected. Inherits Global ~~~~~~ BC30179: structure '[Global]' and class 'Global' conflict in namespace '&lt;Default&gt;'. Structure [Global] ~~~~~~~~ BC30179: class 'Global' and structure 'Global' conflict in namespace '&lt;Default&gt;'. Class Global ~~~~~~ BC30183: Keyword is not valid as an identifier. Class Global ~~~~~~ </errors>) End Sub ' Global can't be used as identifier <WorkItem(527728, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527728")> <Fact> Public Sub BC30183ERR_InvalidUseOfKeyword_GlobalAsIdentifier() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Class Global(Of T As Class) End Class Class C1(Of Global As Class) End Class </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "Global", "[Global](Of T As Class)", "C1(Of [Global] As Class)") CompilationUtils.AssertTheseParseDiagnostics(compilation1, <errors> BC30183: Keyword is not valid as an identifier. Class Global(Of T As Class) ~~~~~~ BC30183: Keyword is not valid as an identifier. Class C1(Of Global As Class) ~~~~~~ </errors>) End Sub ' Global can't be used as Access Modifier <Fact> Public Sub BC30035ERR_Syntax_AccessModifier() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Global Class C1(of T as class) End Class </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "C1(Of T As Class)") CompilationUtils.AssertTheseParseDiagnostics(compilation1, <errors> BC30188: Declaration expected. Global Class C1(of T as class) ~~~~~~ </errors>) End Sub ' Global namespace may not be nested in another namespace <WorkItem(539076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539076")> <Fact> Public Sub BC31544ERR_NestedGlobalNamespace_NestedGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Namespace Global ' invalid Public Class c1 End Class End Namespace End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1") Assert.Equal("[Global]", compilation1.SourceModule.GlobalNamespace.GetMembers().Single().ToDisplayString()) CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors> BC31544: Global namespace may not be nested in another namespace. Namespace Global ' invalid ~~~~~~ </errors>) End Sub ' [Global] namespace could be nested in another namespace <Fact> Public Sub NestedEscapedGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Namespace [Global] ' valid Public Class C1 End Class End Namespace End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "[Global].C1") CompilationUtils.AssertNoDeclarationDiagnostics(compilation1) End Sub ' Global in Fully qualified names <Fact> Public Sub FullyQualifiedOfGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Imports [Global].ns1 Namespace Global.Global.ns1 Class C1 End Class End Namespace Namespace [Global].ns1 Class C1 End Class End Namespace </file> <file name="b.vb"> Imports NS1.Global'valid NS1.Global considered NS1.[Global] Namespace NS1 Namespace [Global] Public Class C2 End Class End Namespace End Namespace </file> <file name="c.vb"> Namespace ns1.Global 'valid considered NS1.[Global] Public Class C2 End Class End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", {"[Global].ns1.C1", "[Global].ns1.C1"}, False) CompilationUtils.VerifyGlobalNamespace(compilation1, "b.vb", "C2", "NS1.Global.C2") CompilationUtils.VerifyGlobalNamespace(compilation1, "c.vb", "C2", "NS1.Global.C2") CompilationUtils.AssertTheseDiagnostics(compilation1, <errors> BC30179: class 'C1' and class 'C1' conflict in namespace '[Global].ns1'. Class C1 ~~ BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'NS1' in 'b.vb'. Namespace ns1.Global 'valid considered NS1.[Global] ~~~ BC30179: class 'C2' and class 'C2' conflict in namespace 'NS1.Global'. Public Class C2 ~~ </errors>) End Sub ' Different types in global namespace <Fact> Public Sub DiffTypeInGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="comp1"> <file name="a.vb"> Namespace Global Class [Global] Class UserdefCls End Class Structure UserdefStruct End Structure End Class Module M1 End Module Enum E1 ONE End Enum End Namespace </file> </compilation>) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "UserdefCls", "[Global].UserdefCls") CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "UserdefStruct", "[Global].UserdefStruct") CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "M1", "M1") CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "E1", "E1") CompilationUtils.AssertNoErrors(compilation1) End Sub ' Access different fields with different access modifiers in Global <Fact> Public Sub DiffAccessInGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Public Class C1 Private Class C2 End Class Friend Class C3 End Class End Class End Namespace </file> </compilation>) Dim symbolC1 = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "C1") Dim symbolC2 = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C2", "C1.C2") Dim symbolC3 = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C3", "C1.C3") Assert.Equal(Accessibility.Public, symbolC1(0).DeclaredAccessibility) Assert.Equal(Accessibility.Private, symbolC2(0).DeclaredAccessibility) Assert.Equal(Accessibility.Friend, symbolC3(0).DeclaredAccessibility) End Sub ' Global works on Compilation <WorkItem(539077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539077")> <Fact> Public Sub BC30554ERR_AmbiguousInUnnamedNamespace1_GlobalOnCompilation() Dim opt1 = TestOptions.ReleaseDll.WithRootNamespace("NS1") Dim opt2 = TestOptions.ReleaseDll.WithRootNamespace("NS2") Dim opt3 = TestOptions.ReleaseDll.WithRootNamespace("NS3") Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Public Class C1 Private Class C2 End Class Public Class C3 End Class End Class End Namespace </file> </compilation>, options:=opt1) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp2"> <file name="a.vb"> Namespace Global Public Class C1 Private Class C2 End Class Public Class C3 End Class End Class End Namespace </file> </compilation>, options:=opt2) Dim ref1 = New VisualBasicCompilationReference(compilation1) Dim ref2 = New VisualBasicCompilationReference(compilation2) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp3"> <file name="a.vb"> Namespace NS1 Structure S1 Dim A As Global.C1.C2 ' invalid Dim B As Global.C1.C3 ' invalid End Structure End Namespace </file> </compilation>, options:=opt3) compilation3 = compilation3.AddReferences(ref1, ref2) CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C2", "C1.C2") CompilationUtils.VerifyGlobalNamespace(compilation2, "a.vb", "C3", "C1.C3") CompilationUtils.AssertTheseDiagnostics(compilation3, <errors> BC30554: 'C1' is ambiguous. Dim A As Global.C1.C2 ' invalid ~~~~~~~~~ BC30554: 'C1' is ambiguous. Dim B As Global.C1.C3 ' invalid ~~~~~~~~~ </errors>) End Sub ' Define customer namespace same as namespace of the .NET Framework in Global <Fact> Public Sub DefSystemNSInGlobal() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="comp1"> <file name="a.vb"> Namespace Global Namespace System Class C1 Dim A As System.Int32 ' valid End Class End Namespace End Namespace </file> </compilation>) Dim symbolC1 = CompilationUtils.VerifyGlobalNamespace(compilation1, "a.vb", "C1", "System.C1") CompilationUtils.AssertNoErrors(compilation1) End Sub <Fact> <WorkItem(545787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545787")> Public Sub NestedGlobalNS() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="NestedGlobalNS"> <file name="a.vb"> Imports System Namespace N Namespace Global.M Class X 'BIND:"Class X" End Class End Namespace End Namespace </file> </compilation>) Dim model = GetSemanticModel(compilation, "a.vb") Dim typeStatementSyntax = CompilationUtils.FindBindingText(Of TypeStatementSyntax)(compilation, "a.vb", 0) Dim cls = DirectCast(model.GetDeclaredSymbol(typeStatementSyntax), NamedTypeSymbol) Assert.Equal("N.Global.M.X", cls.ToDisplayString()) End Sub <Fact> Public Sub Bug529716() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace Global Class C End Class End Namespace Namespace Global.Ns1 Class D End Class End Namespace </file> </compilation>) Dim [global] = compilation1.SourceModule.GlobalNamespace Dim classC = [global].GetTypeMembers("C").Single() Dim ns1 = DirectCast([global].GetMembers("Ns1").Single(), NamespaceSymbol) Dim classD = ns1.GetTypeMembers("D").Single() Assert.False(ns1.IsImplicitlyDeclared) For Each ref In [global].DeclaringSyntaxReferences Dim node = ref.GetSyntax() Assert.Equal(SyntaxKind.CompilationUnit, node.Kind) Next ' Since we never return something other than CompilationUnit as a declaring syntax for a Global namespace, ' the following assert should succeed. Assert.True([global].IsImplicitlyDeclared) End Sub End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/Core/Portable/GenerateMember/GenerateConstructor/AbstractGenerateConstructorService.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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> { protected internal class State { private readonly TService _service; private readonly SemanticDocument _document; private readonly NamingRule _fieldNamingRule; private readonly NamingRule _propertyNamingRule; private readonly NamingRule _parameterNamingRule; private ImmutableArray<Argument> _arguments; // The type we're creating a constructor for. Will be a class or struct type. public INamedTypeSymbol? TypeToGenerateIn { get; private set; } private ImmutableArray<RefKind> _parameterRefKinds; public ImmutableArray<ITypeSymbol> ParameterTypes; public SyntaxToken Token { get; private set; } public bool IsConstructorInitializerGeneration { get; private set; } private IMethodSymbol? _delegatedConstructor; private ImmutableArray<IParameterSymbol> _parameters; private ImmutableDictionary<string, ISymbol>? _parameterToExistingMemberMap; public ImmutableDictionary<string, string> ParameterToNewFieldMap { get; private set; } public ImmutableDictionary<string, string> ParameterToNewPropertyMap { get; private set; } public bool IsContainedInUnsafeType { get; private set; } private State(TService service, SemanticDocument document, NamingRule fieldNamingRule, NamingRule propertyNamingRule, NamingRule parameterNamingRule) { _service = service; _document = document; _fieldNamingRule = fieldNamingRule; _propertyNamingRule = propertyNamingRule; _parameterNamingRule = parameterNamingRule; ParameterToNewFieldMap = ImmutableDictionary<string, string>.Empty; ParameterToNewPropertyMap = ImmutableDictionary<string, string>.Empty; } public static async Task<State?> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var fieldNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, cancellationToken).ConfigureAwait(false); var propertyNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Property, Accessibility.Public, cancellationToken).ConfigureAwait(false); var parameterNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Parameter, Accessibility.NotApplicable, cancellationToken).ConfigureAwait(false); var state = new State(service, document, fieldNamingRule, propertyNamingRule, parameterNamingRule); if (!await state.TryInitializeAsync(node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( SyntaxNode node, CancellationToken cancellationToken) { if (_service.IsConstructorInitializerGeneration(_document, node, cancellationToken)) { if (!await TryInitializeConstructorInitializerGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsSimpleNameGeneration(_document, node, cancellationToken)) { if (!await TryInitializeSimpleNameGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsImplicitObjectCreation(_document, node, cancellationToken)) { if (!await TryInitializeImplicitObjectCreationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else { return false; } Contract.ThrowIfNull(TypeToGenerateIn); if (!CodeGenerator.CanAdd(_document.Project.Solution, TypeToGenerateIn, cancellationToken)) return false; ParameterTypes = ParameterTypes.IsDefault ? GetParameterTypes(cancellationToken) : ParameterTypes; _parameterRefKinds = _arguments.SelectAsArray(a => a.RefKind); if (ClashesWithExistingConstructor()) return false; if (!TryInitializeDelegatedConstructor(cancellationToken)) InitializeNonDelegatedConstructor(cancellationToken); IsContainedInUnsafeType = _service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); return true; } private void InitializeNonDelegatedConstructor(CancellationToken cancellationToken) { var typeParametersNames = TypeToGenerateIn.GetAllTypeParameters().Select(t => t.Name).ToImmutableArray(); var parameterNames = GetParameterNames(_arguments, typeParametersNames, cancellationToken); GetParameters(_arguments, ParameterTypes, parameterNames, cancellationToken); } private ImmutableArray<ParameterName> GetParameterNames( ImmutableArray<Argument> arguments, ImmutableArray<string> typeParametersNames, CancellationToken cancellationToken) { return _service.GenerateParameterNames(_document, arguments, typeParametersNames, _parameterNamingRule, cancellationToken); } private bool TryInitializeDelegatedConstructor(CancellationToken cancellationToken) { var parameters = ParameterTypes.Zip(_parameterRefKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray(); var expressions = _arguments.SelectAsArray(a => a.Expression); var delegatedConstructor = FindConstructorToDelegateTo(parameters, expressions, cancellationToken); if (delegatedConstructor == null) return false; // Map the first N parameters to the other constructor in this type. Then // try to map any further parameters to existing fields. Finally, generate // new fields if no such parameters exist. // Find the names of the parameters that will follow the parameters we're // delegating. var argumentCount = delegatedConstructor.Parameters.Length; var remainingArguments = _arguments.Skip(argumentCount).ToImmutableArray(); var remainingParameterNames = _service.GenerateParameterNames( _document, remainingArguments, delegatedConstructor.Parameters.Select(p => p.Name).ToList(), _parameterNamingRule, cancellationToken); // Can't generate the constructor if the parameter names we're copying over forcibly // conflict with any names we generated. if (delegatedConstructor.Parameters.Select(p => p.Name).Intersect(remainingParameterNames.Select(n => n.BestNameForParameter)).Any()) return false; var remainingParameterTypes = ParameterTypes.Skip(argumentCount).ToImmutableArray(); _delegatedConstructor = delegatedConstructor; GetParameters(remainingArguments, remainingParameterTypes, remainingParameterNames, cancellationToken); return true; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> allParameters, ImmutableArray<TExpressionSyntax?> allExpressions, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); Contract.ThrowIfNull(TypeToGenerateIn.BaseType); for (var i = allParameters.Length; i > 0; i--) { var parameters = allParameters.TakeAsArray(i); var expressions = allExpressions.TakeAsArray(i); var result = FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.InstanceConstructors, cancellationToken) ?? FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.BaseType.InstanceConstructors, cancellationToken); if (result != null) return result; } return null; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, ImmutableArray<IMethodSymbol> constructors, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); foreach (var constructor in constructors) { // Don't bother delegating to an implicit constructor. We don't want to add `: base()` as that's just // redundant for subclasses and `: this()` won't even work as we won't have an implicit constructor once // we add this new constructor. if (constructor.IsImplicitlyDeclared) continue; // Don't delegate to another constructor in this type if it's got the same parameter types as the // one we're generating. This can happen if we're generating the new constructor because parameter // names don't match (when a user explicitly provides named parameters). if (TypeToGenerateIn.Equals(constructor.ContainingType) && constructor.Parameters.Select(p => p.Type).SequenceEqual(ParameterTypes)) { continue; } if (GenerateConstructorHelpers.CanDelegateTo(_document, parameters, expressions, constructor) && !_service.WillCauseConstructorCycle(this, _document, constructor, cancellationToken)) { return constructor; } } return null; } private bool ClashesWithExistingConstructor() { Contract.ThrowIfNull(TypeToGenerateIn); var destinationProvider = _document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetRequiredService<ISyntaxFactsService>(); return TypeToGenerateIn.InstanceConstructors.Any(c => Matches(c, syntaxFacts)); } private bool Matches(IMethodSymbol ctor, ISyntaxFactsService service) { if (ctor.Parameters.Length != ParameterTypes.Length) return false; for (var i = 0; i < ParameterTypes.Length; i++) { var ctorParameter = ctor.Parameters[i]; var result = SymbolEquivalenceComparer.Instance.Equals(ctorParameter.Type, ParameterTypes[i]) && ctorParameter.RefKind == _parameterRefKinds[i]; var parameterName = GetParameterName(i); if (!string.IsNullOrEmpty(parameterName)) { result &= service.IsCaseSensitive ? ctorParameter.Name == parameterName : string.Equals(ctorParameter.Name, parameterName, StringComparison.OrdinalIgnoreCase); } if (result == false) return false; } return true; } private string GetParameterName(int index) => _arguments.IsDefault || index >= _arguments.Length ? string.Empty : _arguments[index].Name; internal ImmutableArray<ITypeSymbol> GetParameterTypes(CancellationToken cancellationToken) { var allTypeParameters = TypeToGenerateIn.GetAllTypeParameters(); var semanticModel = _document.SemanticModel; var allTypes = _arguments.Select(a => _service.GetArgumentType(_document.SemanticModel, a, cancellationToken)); return allTypes.Select(t => FixType(t, semanticModel, allTypeParameters)).ToImmutableArray(); } private static ITypeSymbol FixType(ITypeSymbol typeSymbol, SemanticModel semanticModel, IEnumerable<ITypeParameterSymbol> allTypeParameters) { var compilation = semanticModel.Compilation; return typeSymbol.RemoveAnonymousTypes(compilation) .RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation); } private async Task<bool> TryInitializeConstructorInitializerGenerationAsync( SyntaxNode constructorInitializer, CancellationToken cancellationToken) { if (_service.TryInitializeConstructorInitializerGeneration( _document, constructorInitializer, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; IsConstructorInitializerGeneration = true; var semanticInfo = _document.SemanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeImplicitObjectCreationAsync(SyntaxNode implicitObjectCreation, CancellationToken cancellationToken) { if (_service.TryInitializeImplicitObjectCreation( _document, implicitObjectCreation, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; var semanticInfo = _document.SemanticModel.GetSymbolInfo(implicitObjectCreation, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeSimpleNameGenerationAsync( SyntaxNode simpleName, CancellationToken cancellationToken) { if (_service.TryInitializeSimpleNameGenerationState( _document, simpleName, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; } else if (_service.TryInitializeSimpleAttributeNameGenerationState( _document, simpleName, cancellationToken, out token, out arguments, out typeToGenerateIn)) { Token = token; _arguments = arguments; //// Attribute parameters are restricted to be constant values (simple types or string, etc). if (GetParameterTypes(cancellationToken).Any(t => !IsValidAttributeParameterType(t))) return false; } else { return false; } cancellationToken.ThrowIfCancellationRequested(); return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } private static bool IsValidAttributeParameterType(ITypeSymbol type) { if (type.Kind == SymbolKind.ArrayType) { var arrayType = (IArrayTypeSymbol)type; if (arrayType.Rank != 1) { return false; } type = arrayType.ElementType; } if (type.IsEnumType()) { return true; } switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_String: return true; default: return false; } } private async Task<bool> TryDetermineTypeToGenerateInAsync( INamedTypeSymbol original, CancellationToken cancellationToken) { var definition = await SymbolFinder.FindSourceDefinitionAsync(original, _document.Project.Solution, cancellationToken).ConfigureAwait(false); TypeToGenerateIn = definition as INamedTypeSymbol; return TypeToGenerateIn?.TypeKind is (TypeKind?)TypeKind.Class or (TypeKind?)TypeKind.Struct; } private void GetParameters( ImmutableArray<Argument> arguments, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<ParameterName> parameterNames, CancellationToken cancellationToken) { var parameterToExistingMemberMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>(); var parameterToNewPropertyMap = ImmutableDictionary.CreateBuilder<string, string>(); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters); for (var i = 0; i < parameterNames.Length; i++) { var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; var argument = arguments[i]; // See if there's a matching field or property we can use, or create a new member otherwise. FindExistingOrCreateNewMember( ref parameterName, parameterType, argument, parameterToExistingMemberMap, parameterToNewFieldMap, parameterToNewPropertyMap, cancellationToken); parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: argument.RefKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } _parameters = parameters.ToImmutable(); _parameterToExistingMemberMap = parameterToExistingMemberMap.ToImmutable(); ParameterToNewFieldMap = parameterToNewFieldMap.ToImmutable(); ParameterToNewPropertyMap = parameterToNewPropertyMap.ToImmutable(); } private void FindExistingOrCreateNewMember( ref ParameterName parameterName, ITypeSymbol parameterType, Argument argument, ImmutableDictionary<string, ISymbol>.Builder parameterToExistingMemberMap, ImmutableDictionary<string, string>.Builder parameterToNewFieldMap, ImmutableDictionary<string, string>.Builder parameterToNewPropertyMap, CancellationToken cancellationToken) { var expectedFieldName = _fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var expectedPropertyName = _propertyNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var isFixed = argument.IsNamed; // For non-out parameters, see if there's already a field there with the same name. // If so, and it has a compatible type, then we can just assign to that field. // Otherwise, we'll need to choose a different name for this member so that it // doesn't conflict with something already in the type. First check the current type // for a matching field. If so, defer to it. var unavailableMemberNames = GetUnavailableMemberNames().ToImmutableArray(); var members = from t in TypeToGenerateIn.GetBaseTypesAndThis() let ignoreAccessibility = t.Equals(TypeToGenerateIn) from m in t.GetMembers() where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase) where ignoreAccessibility || IsSymbolAccessible(m, _document) select m; var membersArray = members.ToImmutableArray(); var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault(); if (symbol != null) { if (IsViableFieldOrProperty(parameterType, symbol)) { // Ok! We can just the existing field. parameterToExistingMemberMap[parameterName.BestNameForParameter] = symbol; } else { // Uh-oh. Now we have a problem. We can't assign this parameter to // this field. So we need to create a new field. Find a name not in // use so we can assign to that. var baseName = _service.GenerateNameForArgument(_document.SemanticModel, argument, cancellationToken); var baseFieldWithNamingStyle = _fieldNamingRule.NamingStyle.MakeCompliant(baseName).First(); var basePropertyWithNamingStyle = _propertyNamingRule.NamingStyle.MakeCompliant(baseName).First(); var newFieldName = NameGenerator.EnsureUniqueness(baseFieldWithNamingStyle, unavailableMemberNames.Concat(parameterToNewFieldMap.Values)); var newPropertyName = NameGenerator.EnsureUniqueness(basePropertyWithNamingStyle, unavailableMemberNames.Concat(parameterToNewPropertyMap.Values)); if (isFixed) { // Can't change the parameter name, so map the existing parameter // name to the new field name. parameterToNewFieldMap[parameterName.NameBasedOnArgument] = newFieldName; parameterToNewPropertyMap[parameterName.NameBasedOnArgument] = newPropertyName; } else { // Can change the parameter name, so do so. // But first remove any prefix added due to field naming styles var fieldNameMinusPrefix = newFieldName[_fieldNamingRule.NamingStyle.Prefix.Length..]; var newParameterName = new ParameterName(fieldNameMinusPrefix, isFixed: false, _parameterNamingRule); parameterName = newParameterName; parameterToNewFieldMap[newParameterName.BestNameForParameter] = newFieldName; parameterToNewPropertyMap[newParameterName.BestNameForParameter] = newPropertyName; } } return; } // If no matching field was found, use the fieldNamingRule to create suitable name var bestNameForParameter = parameterName.BestNameForParameter; var nameBasedOnArgument = parameterName.NameBasedOnArgument; parameterToNewFieldMap[bestNameForParameter] = _fieldNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); parameterToNewPropertyMap[bestNameForParameter] = _propertyNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); } private IEnumerable<string> GetUnavailableMemberNames() { Contract.ThrowIfNull(TypeToGenerateIn); return TypeToGenerateIn.MemberNames.Concat( from type in TypeToGenerateIn.GetBaseTypes() from member in type.GetMembers() select member.Name); } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (parameterType.Language != symbol.Language) return false; if (symbol != null && !symbol.IsStatic) { if (symbol is IFieldSymbol field) { return !field.IsConst && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol property) { return property.Parameters.Length == 0 && property.IsWritableInConstructor() && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type); } } return false; } public async Task<Document> GetChangedDocumentAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { // See if there's an accessible base constructor that would accept these // types, then just call into that instead of generating fields. // // then, see if there are any constructors that would take the first 'n' arguments // we've provided. If so, delegate to those, and then create a field for any // remaining arguments. Try to match from largest to smallest. // // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. return await GenerateThisOrBaseDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false) ?? await GenerateMemberDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); } private async Task<Document?> GenerateThisOrBaseDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { if (_delegatedConstructor == null) return null; Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var (members, assignments) = await GenerateMembersAndAssignmentsAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); var isThis = _delegatedConstructor.ContainingType.OriginalDefinition.Equals(TypeToGenerateIn.OriginalDefinition); var delegatingArguments = provider.GetService<SyntaxGenerator>().CreateArguments(_delegatedConstructor.Parameters); var newParameters = _delegatedConstructor.Parameters.Concat(_parameters); var generateUnsafe = !IsContainedInUnsafeType && newParameters.Any(p => p.RequiresUnsafeModifier()); var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isUnsafe: generateUnsafe), typeName: TypeToGenerateIn.Name, parameters: newParameters, statements: assignments, baseConstructorArguments: isThis ? default : delegatingArguments, thisConstructorArguments: isThis ? delegatingArguments : default); return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, members.Concat(constructor), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } private async Task<(ImmutableArray<ISymbol>, ImmutableArray<SyntaxNode>)> GenerateMembersAndAssignmentsAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var members = withFields ? SyntaxGeneratorExtensions.CreateFieldsForParameters(_parameters, ParameterToNewFieldMap, IsContainedInUnsafeType) : withProperties ? SyntaxGeneratorExtensions.CreatePropertiesForParameters(_parameters, ParameterToNewPropertyMap, IsContainedInUnsafeType) : ImmutableArray<ISymbol>.Empty; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var assignments = !withFields && !withProperties ? ImmutableArray<SyntaxNode>.Empty : provider.GetService<SyntaxGenerator>().CreateAssignmentStatements( semanticModel, _parameters, _parameterToExistingMemberMap, withFields ? ParameterToNewFieldMap : ParameterToNewPropertyMap, addNullChecks: false, preferThrowExpression: false); return (members, assignments); } private async Task<Document> GenerateMemberDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newMemberMap = withFields ? ParameterToNewFieldMap : withProperties ? ParameterToNewPropertyMap : ImmutableDictionary<string, string>.Empty; return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, provider.GetService<SyntaxGenerator>().CreateMemberDelegatingConstructor( semanticModel, TypeToGenerateIn.Name, TypeToGenerateIn, _parameters, _parameterToExistingMemberMap, newMemberMap, addNullChecks: false, preferThrowExpression: false, generateProperties: withProperties, IsContainedInUnsafeType), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> { protected internal class State { private readonly TService _service; private readonly SemanticDocument _document; private readonly NamingRule _fieldNamingRule; private readonly NamingRule _propertyNamingRule; private readonly NamingRule _parameterNamingRule; private ImmutableArray<Argument> _arguments; // The type we're creating a constructor for. Will be a class or struct type. public INamedTypeSymbol? TypeToGenerateIn { get; private set; } private ImmutableArray<RefKind> _parameterRefKinds; public ImmutableArray<ITypeSymbol> ParameterTypes; public SyntaxToken Token { get; private set; } public bool IsConstructorInitializerGeneration { get; private set; } private IMethodSymbol? _delegatedConstructor; private ImmutableArray<IParameterSymbol> _parameters; private ImmutableDictionary<string, ISymbol>? _parameterToExistingMemberMap; public ImmutableDictionary<string, string> ParameterToNewFieldMap { get; private set; } public ImmutableDictionary<string, string> ParameterToNewPropertyMap { get; private set; } public bool IsContainedInUnsafeType { get; private set; } private State(TService service, SemanticDocument document, NamingRule fieldNamingRule, NamingRule propertyNamingRule, NamingRule parameterNamingRule) { _service = service; _document = document; _fieldNamingRule = fieldNamingRule; _propertyNamingRule = propertyNamingRule; _parameterNamingRule = parameterNamingRule; ParameterToNewFieldMap = ImmutableDictionary<string, string>.Empty; ParameterToNewPropertyMap = ImmutableDictionary<string, string>.Empty; } public static async Task<State?> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var fieldNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, cancellationToken).ConfigureAwait(false); var propertyNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Property, Accessibility.Public, cancellationToken).ConfigureAwait(false); var parameterNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Parameter, Accessibility.NotApplicable, cancellationToken).ConfigureAwait(false); var state = new State(service, document, fieldNamingRule, propertyNamingRule, parameterNamingRule); if (!await state.TryInitializeAsync(node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( SyntaxNode node, CancellationToken cancellationToken) { if (_service.IsConstructorInitializerGeneration(_document, node, cancellationToken)) { if (!await TryInitializeConstructorInitializerGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsSimpleNameGeneration(_document, node, cancellationToken)) { if (!await TryInitializeSimpleNameGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsImplicitObjectCreation(_document, node, cancellationToken)) { if (!await TryInitializeImplicitObjectCreationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else { return false; } Contract.ThrowIfNull(TypeToGenerateIn); if (!CodeGenerator.CanAdd(_document.Project.Solution, TypeToGenerateIn, cancellationToken)) return false; ParameterTypes = ParameterTypes.IsDefault ? GetParameterTypes(cancellationToken) : ParameterTypes; _parameterRefKinds = _arguments.SelectAsArray(a => a.RefKind); if (ClashesWithExistingConstructor()) return false; if (!TryInitializeDelegatedConstructor(cancellationToken)) InitializeNonDelegatedConstructor(cancellationToken); IsContainedInUnsafeType = _service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); return true; } private void InitializeNonDelegatedConstructor(CancellationToken cancellationToken) { var typeParametersNames = TypeToGenerateIn.GetAllTypeParameters().Select(t => t.Name).ToImmutableArray(); var parameterNames = GetParameterNames(_arguments, typeParametersNames, cancellationToken); GetParameters(_arguments, ParameterTypes, parameterNames, cancellationToken); } private ImmutableArray<ParameterName> GetParameterNames( ImmutableArray<Argument> arguments, ImmutableArray<string> typeParametersNames, CancellationToken cancellationToken) { return _service.GenerateParameterNames(_document, arguments, typeParametersNames, _parameterNamingRule, cancellationToken); } private bool TryInitializeDelegatedConstructor(CancellationToken cancellationToken) { var parameters = ParameterTypes.Zip(_parameterRefKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray(); var expressions = _arguments.SelectAsArray(a => a.Expression); var delegatedConstructor = FindConstructorToDelegateTo(parameters, expressions, cancellationToken); if (delegatedConstructor == null) return false; // Map the first N parameters to the other constructor in this type. Then // try to map any further parameters to existing fields. Finally, generate // new fields if no such parameters exist. // Find the names of the parameters that will follow the parameters we're // delegating. var argumentCount = delegatedConstructor.Parameters.Length; var remainingArguments = _arguments.Skip(argumentCount).ToImmutableArray(); var remainingParameterNames = _service.GenerateParameterNames( _document, remainingArguments, delegatedConstructor.Parameters.Select(p => p.Name).ToList(), _parameterNamingRule, cancellationToken); // Can't generate the constructor if the parameter names we're copying over forcibly // conflict with any names we generated. if (delegatedConstructor.Parameters.Select(p => p.Name).Intersect(remainingParameterNames.Select(n => n.BestNameForParameter)).Any()) return false; var remainingParameterTypes = ParameterTypes.Skip(argumentCount).ToImmutableArray(); _delegatedConstructor = delegatedConstructor; GetParameters(remainingArguments, remainingParameterTypes, remainingParameterNames, cancellationToken); return true; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> allParameters, ImmutableArray<TExpressionSyntax?> allExpressions, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); Contract.ThrowIfNull(TypeToGenerateIn.BaseType); for (var i = allParameters.Length; i > 0; i--) { var parameters = allParameters.TakeAsArray(i); var expressions = allExpressions.TakeAsArray(i); var result = FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.InstanceConstructors, cancellationToken) ?? FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.BaseType.InstanceConstructors, cancellationToken); if (result != null) return result; } return null; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, ImmutableArray<IMethodSymbol> constructors, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); foreach (var constructor in constructors) { // Don't bother delegating to an implicit constructor. We don't want to add `: base()` as that's just // redundant for subclasses and `: this()` won't even work as we won't have an implicit constructor once // we add this new constructor. if (constructor.IsImplicitlyDeclared) continue; // Don't delegate to another constructor in this type if it's got the same parameter types as the // one we're generating. This can happen if we're generating the new constructor because parameter // names don't match (when a user explicitly provides named parameters). if (TypeToGenerateIn.Equals(constructor.ContainingType) && constructor.Parameters.Select(p => p.Type).SequenceEqual(ParameterTypes)) { continue; } if (GenerateConstructorHelpers.CanDelegateTo(_document, parameters, expressions, constructor) && !_service.WillCauseConstructorCycle(this, _document, constructor, cancellationToken)) { return constructor; } } return null; } private bool ClashesWithExistingConstructor() { Contract.ThrowIfNull(TypeToGenerateIn); var destinationProvider = _document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetRequiredService<ISyntaxFactsService>(); return TypeToGenerateIn.InstanceConstructors.Any(c => Matches(c, syntaxFacts)); } private bool Matches(IMethodSymbol ctor, ISyntaxFactsService service) { if (ctor.Parameters.Length != ParameterTypes.Length) return false; for (var i = 0; i < ParameterTypes.Length; i++) { var ctorParameter = ctor.Parameters[i]; var result = SymbolEquivalenceComparer.Instance.Equals(ctorParameter.Type, ParameterTypes[i]) && ctorParameter.RefKind == _parameterRefKinds[i]; var parameterName = GetParameterName(i); if (!string.IsNullOrEmpty(parameterName)) { result &= service.IsCaseSensitive ? ctorParameter.Name == parameterName : string.Equals(ctorParameter.Name, parameterName, StringComparison.OrdinalIgnoreCase); } if (result == false) return false; } return true; } private string GetParameterName(int index) => _arguments.IsDefault || index >= _arguments.Length ? string.Empty : _arguments[index].Name; internal ImmutableArray<ITypeSymbol> GetParameterTypes(CancellationToken cancellationToken) { var allTypeParameters = TypeToGenerateIn.GetAllTypeParameters(); var semanticModel = _document.SemanticModel; var allTypes = _arguments.Select(a => _service.GetArgumentType(_document.SemanticModel, a, cancellationToken)); return allTypes.Select(t => FixType(t, semanticModel, allTypeParameters)).ToImmutableArray(); } private static ITypeSymbol FixType(ITypeSymbol typeSymbol, SemanticModel semanticModel, IEnumerable<ITypeParameterSymbol> allTypeParameters) { var compilation = semanticModel.Compilation; return typeSymbol.RemoveAnonymousTypes(compilation) .RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation); } private async Task<bool> TryInitializeConstructorInitializerGenerationAsync( SyntaxNode constructorInitializer, CancellationToken cancellationToken) { if (_service.TryInitializeConstructorInitializerGeneration( _document, constructorInitializer, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; IsConstructorInitializerGeneration = true; var semanticInfo = _document.SemanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeImplicitObjectCreationAsync(SyntaxNode implicitObjectCreation, CancellationToken cancellationToken) { if (_service.TryInitializeImplicitObjectCreation( _document, implicitObjectCreation, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; var semanticInfo = _document.SemanticModel.GetSymbolInfo(implicitObjectCreation, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeSimpleNameGenerationAsync( SyntaxNode simpleName, CancellationToken cancellationToken) { if (_service.TryInitializeSimpleNameGenerationState( _document, simpleName, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; } else if (_service.TryInitializeSimpleAttributeNameGenerationState( _document, simpleName, cancellationToken, out token, out arguments, out typeToGenerateIn)) { Token = token; _arguments = arguments; //// Attribute parameters are restricted to be constant values (simple types or string, etc). if (GetParameterTypes(cancellationToken).Any(t => !IsValidAttributeParameterType(t))) return false; } else { return false; } cancellationToken.ThrowIfCancellationRequested(); return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } private static bool IsValidAttributeParameterType(ITypeSymbol type) { if (type.Kind == SymbolKind.ArrayType) { var arrayType = (IArrayTypeSymbol)type; if (arrayType.Rank != 1) { return false; } type = arrayType.ElementType; } if (type.IsEnumType()) { return true; } switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_String: return true; default: return false; } } private async Task<bool> TryDetermineTypeToGenerateInAsync( INamedTypeSymbol original, CancellationToken cancellationToken) { var definition = await SymbolFinder.FindSourceDefinitionAsync(original, _document.Project.Solution, cancellationToken).ConfigureAwait(false); TypeToGenerateIn = definition as INamedTypeSymbol; return TypeToGenerateIn?.TypeKind is (TypeKind?)TypeKind.Class or (TypeKind?)TypeKind.Struct; } private void GetParameters( ImmutableArray<Argument> arguments, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<ParameterName> parameterNames, CancellationToken cancellationToken) { var parameterToExistingMemberMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>(); var parameterToNewPropertyMap = ImmutableDictionary.CreateBuilder<string, string>(); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters); for (var i = 0; i < parameterNames.Length; i++) { var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; var argument = arguments[i]; // See if there's a matching field or property we can use, or create a new member otherwise. FindExistingOrCreateNewMember( ref parameterName, parameterType, argument, parameterToExistingMemberMap, parameterToNewFieldMap, parameterToNewPropertyMap, cancellationToken); parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: argument.RefKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } _parameters = parameters.ToImmutable(); _parameterToExistingMemberMap = parameterToExistingMemberMap.ToImmutable(); ParameterToNewFieldMap = parameterToNewFieldMap.ToImmutable(); ParameterToNewPropertyMap = parameterToNewPropertyMap.ToImmutable(); } private void FindExistingOrCreateNewMember( ref ParameterName parameterName, ITypeSymbol parameterType, Argument argument, ImmutableDictionary<string, ISymbol>.Builder parameterToExistingMemberMap, ImmutableDictionary<string, string>.Builder parameterToNewFieldMap, ImmutableDictionary<string, string>.Builder parameterToNewPropertyMap, CancellationToken cancellationToken) { var expectedFieldName = _fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var expectedPropertyName = _propertyNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var isFixed = argument.IsNamed; // For non-out parameters, see if there's already a field there with the same name. // If so, and it has a compatible type, then we can just assign to that field. // Otherwise, we'll need to choose a different name for this member so that it // doesn't conflict with something already in the type. First check the current type // for a matching field. If so, defer to it. var unavailableMemberNames = GetUnavailableMemberNames().ToImmutableArray(); var members = from t in TypeToGenerateIn.GetBaseTypesAndThis() let ignoreAccessibility = t.Equals(TypeToGenerateIn) from m in t.GetMembers() where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase) where ignoreAccessibility || IsSymbolAccessible(m, _document) select m; var membersArray = members.ToImmutableArray(); var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault(); if (symbol != null) { if (IsViableFieldOrProperty(parameterType, symbol)) { // Ok! We can just the existing field. parameterToExistingMemberMap[parameterName.BestNameForParameter] = symbol; } else { // Uh-oh. Now we have a problem. We can't assign this parameter to // this field. So we need to create a new field. Find a name not in // use so we can assign to that. var baseName = _service.GenerateNameForArgument(_document.SemanticModel, argument, cancellationToken); var baseFieldWithNamingStyle = _fieldNamingRule.NamingStyle.MakeCompliant(baseName).First(); var basePropertyWithNamingStyle = _propertyNamingRule.NamingStyle.MakeCompliant(baseName).First(); var newFieldName = NameGenerator.EnsureUniqueness(baseFieldWithNamingStyle, unavailableMemberNames.Concat(parameterToNewFieldMap.Values)); var newPropertyName = NameGenerator.EnsureUniqueness(basePropertyWithNamingStyle, unavailableMemberNames.Concat(parameterToNewPropertyMap.Values)); if (isFixed) { // Can't change the parameter name, so map the existing parameter // name to the new field name. parameterToNewFieldMap[parameterName.NameBasedOnArgument] = newFieldName; parameterToNewPropertyMap[parameterName.NameBasedOnArgument] = newPropertyName; } else { // Can change the parameter name, so do so. // But first remove any prefix added due to field naming styles var fieldNameMinusPrefix = newFieldName[_fieldNamingRule.NamingStyle.Prefix.Length..]; var newParameterName = new ParameterName(fieldNameMinusPrefix, isFixed: false, _parameterNamingRule); parameterName = newParameterName; parameterToNewFieldMap[newParameterName.BestNameForParameter] = newFieldName; parameterToNewPropertyMap[newParameterName.BestNameForParameter] = newPropertyName; } } return; } // If no matching field was found, use the fieldNamingRule to create suitable name var bestNameForParameter = parameterName.BestNameForParameter; var nameBasedOnArgument = parameterName.NameBasedOnArgument; parameterToNewFieldMap[bestNameForParameter] = _fieldNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); parameterToNewPropertyMap[bestNameForParameter] = _propertyNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); } private IEnumerable<string> GetUnavailableMemberNames() { Contract.ThrowIfNull(TypeToGenerateIn); return TypeToGenerateIn.MemberNames.Concat( from type in TypeToGenerateIn.GetBaseTypes() from member in type.GetMembers() select member.Name); } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (parameterType.Language != symbol.Language) return false; if (symbol != null && !symbol.IsStatic) { if (symbol is IFieldSymbol field) { return !field.IsConst && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol property) { return property.Parameters.Length == 0 && property.IsWritableInConstructor() && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type); } } return false; } public async Task<Document> GetChangedDocumentAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { // See if there's an accessible base constructor that would accept these // types, then just call into that instead of generating fields. // // then, see if there are any constructors that would take the first 'n' arguments // we've provided. If so, delegate to those, and then create a field for any // remaining arguments. Try to match from largest to smallest. // // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. return await GenerateThisOrBaseDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false) ?? await GenerateMemberDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); } private async Task<Document?> GenerateThisOrBaseDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { if (_delegatedConstructor == null) return null; Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var (members, assignments) = await GenerateMembersAndAssignmentsAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); var isThis = _delegatedConstructor.ContainingType.OriginalDefinition.Equals(TypeToGenerateIn.OriginalDefinition); var delegatingArguments = provider.GetService<SyntaxGenerator>().CreateArguments(_delegatedConstructor.Parameters); var newParameters = _delegatedConstructor.Parameters.Concat(_parameters); var generateUnsafe = !IsContainedInUnsafeType && newParameters.Any(p => p.RequiresUnsafeModifier()); var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isUnsafe: generateUnsafe), typeName: TypeToGenerateIn.Name, parameters: newParameters, statements: assignments, baseConstructorArguments: isThis ? default : delegatingArguments, thisConstructorArguments: isThis ? delegatingArguments : default); return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, members.Concat(constructor), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } private async Task<(ImmutableArray<ISymbol>, ImmutableArray<SyntaxNode>)> GenerateMembersAndAssignmentsAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var members = withFields ? SyntaxGeneratorExtensions.CreateFieldsForParameters(_parameters, ParameterToNewFieldMap, IsContainedInUnsafeType) : withProperties ? SyntaxGeneratorExtensions.CreatePropertiesForParameters(_parameters, ParameterToNewPropertyMap, IsContainedInUnsafeType) : ImmutableArray<ISymbol>.Empty; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var assignments = !withFields && !withProperties ? ImmutableArray<SyntaxNode>.Empty : provider.GetService<SyntaxGenerator>().CreateAssignmentStatements( semanticModel, _parameters, _parameterToExistingMemberMap, withFields ? ParameterToNewFieldMap : ParameterToNewPropertyMap, addNullChecks: false, preferThrowExpression: false); return (members, assignments); } private async Task<Document> GenerateMemberDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newMemberMap = withFields ? ParameterToNewFieldMap : withProperties ? ParameterToNewPropertyMap : ImmutableDictionary<string, string>.Empty; return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, provider.GetService<SyntaxGenerator>().CreateMemberDelegatingConstructor( semanticModel, TypeToGenerateIn.Name, TypeToGenerateIn, _parameters, _parameterToExistingMemberMap, newMemberMap, addNullChecks: false, preferThrowExpression: false, generateProperties: withProperties, IsContainedInUnsafeType), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/EditorFeatures/VisualBasicTest/ChangeSignature/ChangeSignature_Formatting.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 Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_KeepCountsPerLine() As Task Dim markup = <Text><![CDATA[ Class C Sub $$Method(a As Integer, b As Integer, c As Integer, d As Integer, e As Integer, f As Integer) Method(1, 2, 3, 4, 5, 6) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {5, 4, 3, 2, 1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub Method(f As Integer, e As Integer, d As Integer, c As Integer, b As Integer, a As Integer) Method(6, 5, 4, 3, 2, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_SubMethods() As Task Dim markup = <Text><![CDATA[ Class C Sub $$Method(x As Integer, y As Integer) Method(1, 2) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub Method(y As Integer, x As Integer) Method(2, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_FunctionMethods() As Task Dim markup = <Text><![CDATA[ Class C Sub $$Method(x As Integer, y As Integer) Method(1, 2) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub Method(y As Integer, x As Integer) Method(2, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_Events() As Task Dim markup = <Text><![CDATA[ Class C Public Event $$MyEvent(a As Integer, b As Integer) End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Public Event MyEvent(b As Integer, a As Integer) End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_CustomEvents() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(a As Integer, b As Integer) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(a As Integer, b As Integer) End RaiseEvent End Event End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(b As Integer, a As Integer) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(b As Integer, a As Integer) End RaiseEvent End Event End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_Constructors() As Task Dim markup = <Text><![CDATA[ Class C Sub $$New(a As Integer, b As Integer) End Sub Sub M() Dim x = New C(1, 2) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub New(b As Integer, a As Integer) End Sub Sub M() Dim x = New C(2, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_Properties() As Task Dim markup = <Text><![CDATA[ Class C Public Property $$NewProperty(x As Integer, y As Integer) As Integer Get Return 1 End Get Set(value As Integer) End Set End Property Sub M() Dim x = NewProperty(1, 2) NewProperty(1, 2) = x End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Public Property NewProperty(y As Integer, x As Integer) As Integer Get Return 1 End Get Set(value As Integer) End Set End Property Sub M() Dim x = NewProperty(2, 1) NewProperty(2, 1) = x End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_Attribute() As Task Dim markup = <Text><![CDATA[ <Custom(1, 2)> Class CustomAttribute Inherits Attribute Sub $$New(x As Integer, y As Integer) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ <Custom(2, 1)> Class CustomAttribute Inherits Attribute Sub New(y As Integer, x As Integer) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_DelegateFunction() As Task Dim markup = <Text><![CDATA[ Class C Delegate Function $$MyDelegate(x As Integer, y As Integer) End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Function MyDelegate(y As Integer, x As Integer) End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_MultilineSubLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(a As Integer, b As Integer) Sub M(del As MyDelegate) M(Sub(a As Integer, b As Integer) End Sub) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(b As Integer, a As Integer) Sub M(del As MyDelegate) M(Sub(b As Integer, a As Integer) End Sub) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_MultilineFunctionLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Function $$MyDelegate(a As Integer, b As Integer) As Integer Sub M(del As MyDelegate) M(Function(a As Integer, b As Integer) Return 1 End Function) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Function MyDelegate(b As Integer, a As Integer) As Integer Sub M(del As MyDelegate) M(Function(b As Integer, a As Integer) Return 1 End Function) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_SingleLineSubLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(a As Integer, b As Integer) Sub M(del As MyDelegate) M(Sub(a As Integer, b As Integer) System.Console.WriteLine("Test")) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(b As Integer, a As Integer) Sub M(del As MyDelegate) M(Sub(b As Integer, a As Integer) System.Console.WriteLine("Test")) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_SingleLineFunctionLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Function $$MyDelegate(a As Integer, b As Integer) As Integer Sub M(del As MyDelegate) M(Function(a As Integer, b As Integer) 1) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Function MyDelegate(b As Integer, a As Integer) As Integer Sub M(del As MyDelegate) M(Function(b As Integer, a As Integer) 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) 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 Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_KeepCountsPerLine() As Task Dim markup = <Text><![CDATA[ Class C Sub $$Method(a As Integer, b As Integer, c As Integer, d As Integer, e As Integer, f As Integer) Method(1, 2, 3, 4, 5, 6) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {5, 4, 3, 2, 1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub Method(f As Integer, e As Integer, d As Integer, c As Integer, b As Integer, a As Integer) Method(6, 5, 4, 3, 2, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_SubMethods() As Task Dim markup = <Text><![CDATA[ Class C Sub $$Method(x As Integer, y As Integer) Method(1, 2) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub Method(y As Integer, x As Integer) Method(2, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_FunctionMethods() As Task Dim markup = <Text><![CDATA[ Class C Sub $$Method(x As Integer, y As Integer) Method(1, 2) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub Method(y As Integer, x As Integer) Method(2, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_Events() As Task Dim markup = <Text><![CDATA[ Class C Public Event $$MyEvent(a As Integer, b As Integer) End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Public Event MyEvent(b As Integer, a As Integer) End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_CustomEvents() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(a As Integer, b As Integer) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(a As Integer, b As Integer) End RaiseEvent End Event End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(b As Integer, a As Integer) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(b As Integer, a As Integer) End RaiseEvent End Event End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_Constructors() As Task Dim markup = <Text><![CDATA[ Class C Sub $$New(a As Integer, b As Integer) End Sub Sub M() Dim x = New C(1, 2) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Sub New(b As Integer, a As Integer) End Sub Sub M() Dim x = New C(2, 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_Properties() As Task Dim markup = <Text><![CDATA[ Class C Public Property $$NewProperty(x As Integer, y As Integer) As Integer Get Return 1 End Get Set(value As Integer) End Set End Property Sub M() Dim x = NewProperty(1, 2) NewProperty(1, 2) = x End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Public Property NewProperty(y As Integer, x As Integer) As Integer Get Return 1 End Get Set(value As Integer) End Set End Property Sub M() Dim x = NewProperty(2, 1) NewProperty(2, 1) = x End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_Attribute() As Task Dim markup = <Text><![CDATA[ <Custom(1, 2)> Class CustomAttribute Inherits Attribute Sub $$New(x As Integer, y As Integer) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ <Custom(2, 1)> Class CustomAttribute Inherits Attribute Sub New(y As Integer, x As Integer) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_DelegateFunction() As Task Dim markup = <Text><![CDATA[ Class C Delegate Function $$MyDelegate(x As Integer, y As Integer) End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Function MyDelegate(y As Integer, x As Integer) End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_MultilineSubLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(a As Integer, b As Integer) Sub M(del As MyDelegate) M(Sub(a As Integer, b As Integer) End Sub) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(b As Integer, a As Integer) Sub M(del As MyDelegate) M(Sub(b As Integer, a As Integer) End Sub) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_MultilineFunctionLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Function $$MyDelegate(a As Integer, b As Integer) As Integer Sub M(del As MyDelegate) M(Function(a As Integer, b As Integer) Return 1 End Function) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Function MyDelegate(b As Integer, a As Integer) As Integer Sub M(del As MyDelegate) M(Function(b As Integer, a As Integer) Return 1 End Function) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_SingleLineSubLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(a As Integer, b As Integer) Sub M(del As MyDelegate) M(Sub(a As Integer, b As Integer) System.Console.WriteLine("Test")) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(b As Integer, a As Integer) Sub M(del As MyDelegate) M(Sub(b As Integer, a As Integer) System.Console.WriteLine("Test")) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestChangeSignature_Formatting_SingleLineFunctionLambda() As Task Dim markup = <Text><![CDATA[ Class C Delegate Function $$MyDelegate(a As Integer, b As Integer) As Integer Sub M(del As MyDelegate) M(Function(a As Integer, b As Integer) 1) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = {1, 0} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Function MyDelegate(b As Integer, a As Integer) As Integer Sub M(del As MyDelegate) M(Function(b As Integer, a As Integer) 1) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_StringInterpolation.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using System.Diagnostics; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { private BoundExpression RewriteInterpolatedStringConversion(BoundConversion conversion) { Debug.Assert(conversion.ConversionKind == ConversionKind.InterpolatedString); BoundExpression format; ArrayBuilder<BoundExpression> expressions; MakeInterpolatedStringFormat((BoundInterpolatedString)conversion.Operand, out format, out expressions); expressions.Insert(0, format); var stringFactory = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory); // The normal pattern for lowering is to lower subtrees before the enclosing tree. However we cannot lower // the arguments first in this situation because we do not know what conversions will be // produced for the arguments until after we've done overload resolution. So we produce the invocation // and then lower it along with its arguments. var result = _factory.StaticCall(stringFactory, "Create", expressions.ToImmutableAndFree(), allowUnexpandedForm: false // if an interpolation expression is the null literal, it should not match a params parameter. ); if (!result.HasAnyErrors) { result = VisitExpression(result); // lower the arguments AND handle expanded form, argument conversions, etc. result = MakeImplicitConversion(result, conversion.Type); } return result; } /// <summary> /// Rewrites the given interpolated string to the set of handler creation and Append calls, returning an array builder of the append calls and the result /// local temp. /// </summary> /// <remarks>Caller is responsible for freeing the ArrayBuilder</remarks> private (ArrayBuilder<BoundExpression> HandlerPatternExpressions, BoundLocal Result) RewriteToInterpolatedStringHandlerPattern(BoundInterpolatedString node) { Debug.Assert(node.InterpolationData is { Construction: not null }); Debug.Assert(node.Parts.All(static p => p is BoundCall or BoundDynamicInvocation or BoundDynamicMemberAccess or BoundDynamicIndexerAccess)); var data = node.InterpolationData.Value; var builderTempSymbol = _factory.InterpolatedStringHandlerLocal(data.BuilderType, data.ScopeOfContainingExpression, node.Syntax); BoundLocal builderTemp = _factory.Local(builderTempSymbol); // var handler = new HandlerType(baseStringLength, numFormatHoles, ...InterpolatedStringHandlerArgumentAttribute parameters, <optional> out bool appendShouldProceed); var construction = (BoundObjectCreationExpression)data.Construction; BoundLocal? appendShouldProceedLocal = null; if (data.HasTrailingHandlerValidityParameter) { Debug.Assert(construction.ArgumentRefKindsOpt[^1] == RefKind.Out); BoundInterpolatedStringArgumentPlaceholder trailingParameter = data.ArgumentPlaceholders[^1]; TypeSymbol localType = trailingParameter.Type; Debug.Assert(localType.SpecialType == SpecialType.System_Boolean); var outLocal = _factory.SynthesizedLocal(localType); appendShouldProceedLocal = _factory.Local(outLocal); AddPlaceholderReplacement(trailingParameter, appendShouldProceedLocal); } var handlerConstructionAssignment = _factory.AssignmentExpression(builderTemp, (BoundExpression)VisitObjectCreationExpression(construction)); AddPlaceholderReplacement(data.ReceiverPlaceholder, builderTemp); bool usesBoolReturns = data.UsesBoolReturns; var resultExpressions = ArrayBuilder<BoundExpression>.GetInstance(node.Parts.Length + 1); foreach (var part in node.Parts) { if (part is BoundCall call) { Debug.Assert(call.Type.SpecialType == SpecialType.System_Boolean == usesBoolReturns); resultExpressions.Add((BoundExpression)VisitCall(call)); } else if (part is BoundDynamicInvocation dynamicInvocation) { resultExpressions.Add(VisitDynamicInvocation(dynamicInvocation, resultDiscarded: !usesBoolReturns)); } else { throw ExceptionUtilities.UnexpectedValue(part.Kind); } } RemovePlaceholderReplacement(data.ReceiverPlaceholder); if (appendShouldProceedLocal is not null) { RemovePlaceholderReplacement(data.ArgumentPlaceholders[^1]); } if (usesBoolReturns) { // We assume non-bool returns if there was no parts to the string, and code below is predicated on that. Debug.Assert(!node.Parts.IsEmpty); // Start the sequence with appendProceedLocal, if appropriate BoundExpression? currentExpression = appendShouldProceedLocal; var boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); foreach (var appendCall in resultExpressions) { var actualCall = appendCall; if (actualCall.Type!.IsDynamic()) { actualCall = _dynamicFactory.MakeDynamicConversion(actualCall, isExplicit: false, isArrayIndex: false, isChecked: false, boolType).ToExpression(); } // previousAppendCalls && appendCall currentExpression = currentExpression is null ? actualCall : _factory.LogicalAnd(currentExpression, actualCall); } resultExpressions.Clear(); Debug.Assert(currentExpression != null); var sequence = _factory.Sequence( appendShouldProceedLocal is not null ? ImmutableArray.Create(appendShouldProceedLocal.LocalSymbol) : ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create<BoundExpression>(handlerConstructionAssignment), currentExpression); resultExpressions.Add(sequence); } else if (appendShouldProceedLocal is not null && resultExpressions.Count > 0) { // appendCalls Sequence ending in true var appendCallsSequence = _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, resultExpressions.ToImmutableAndClear(), _factory.Literal(value: true)); resultExpressions.Add(handlerConstructionAssignment); // appendShouldProceedLocal && sequence var appendAnd = _factory.LogicalAnd(appendShouldProceedLocal, appendCallsSequence); var result = _factory.Sequence(ImmutableArray.Create(appendShouldProceedLocal.LocalSymbol), resultExpressions.ToImmutableAndClear(), appendAnd); resultExpressions.Add(result); } else if (appendShouldProceedLocal is not null) { // Odd case of no append calls, but with an out param. We don't need to generate any jumps checking the local because there's // nothing to short circuit and avoid, but we do need a sequence to hold the lifetime of the local resultExpressions.Add(_factory.Sequence(ImmutableArray.Create(appendShouldProceedLocal.LocalSymbol), ImmutableArray<BoundExpression>.Empty, handlerConstructionAssignment)); } else { resultExpressions.Insert(0, handlerConstructionAssignment); } return (resultExpressions, builderTemp); } private bool CanLowerToStringConcatenation(BoundInterpolatedString node) { foreach (var part in node.Parts) { if (part is BoundStringInsert fillin) { // this is one of the expression holes if (_inExpressionLambda || fillin.HasErrors || fillin.Value.Type?.SpecialType != SpecialType.System_String || fillin.Alignment != null || fillin.Format != null) { return false; } } } return true; } private void MakeInterpolatedStringFormat(BoundInterpolatedString node, out BoundExpression format, out ArrayBuilder<BoundExpression> expressions) { _factory.Syntax = node.Syntax; int n = node.Parts.Length - 1; var formatString = PooledStringBuilder.GetInstance(); var stringBuilder = formatString.Builder; expressions = ArrayBuilder<BoundExpression>.GetInstance(n + 1); int nextFormatPosition = 0; for (int i = 0; i <= n; i++) { var part = node.Parts[i]; var fillin = part as BoundStringInsert; if (fillin == null) { Debug.Assert(part is BoundLiteral && part.ConstantValue != null); // this is one of the literal parts stringBuilder.Append(part.ConstantValue.StringValue); } else { // this is one of the expression holes stringBuilder.Append('{').Append(nextFormatPosition++); if (fillin.Alignment != null && !fillin.Alignment.HasErrors) { Debug.Assert(fillin.Alignment.ConstantValue is { }); stringBuilder.Append(',').Append(fillin.Alignment.ConstantValue.Int64Value); } if (fillin.Format != null && !fillin.Format.HasErrors) { Debug.Assert(fillin.Format.ConstantValue is { }); stringBuilder.Append(':').Append(fillin.Format.ConstantValue.StringValue); } stringBuilder.Append('}'); var value = fillin.Value; if (value.Type?.TypeKind == TypeKind.Dynamic) { value = MakeConversionNode(value, _compilation.ObjectType, @checked: false); } expressions.Add(value); // NOTE: must still be lowered } } format = _factory.StringLiteral(formatString.ToStringAndFree()); } public override BoundNode VisitInterpolatedString(BoundInterpolatedString node) { Debug.Assert(node.Type is { SpecialType: SpecialType.System_String }); // if target-converted, we should not get here. BoundExpression? result; if (node.InterpolationData is not null) { // If we can lower to the builder pattern, do so. (ArrayBuilder<BoundExpression> handlerPatternExpressions, BoundLocal handlerTemp) = RewriteToInterpolatedStringHandlerPattern(node); // resultTemp = builderTemp.ToStringAndClear(); var toStringAndClear = (MethodSymbol)Binder.GetWellKnownTypeMember(_compilation, WellKnownMember.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear, _diagnostics, syntax: node.Syntax); BoundExpression toStringAndClearCall = toStringAndClear is not null ? BoundCall.Synthesized(node.Syntax, handlerTemp, toStringAndClear) : new BoundBadExpression(node.Syntax, LookupResultKind.Empty, symbols: ImmutableArray<Symbol?>.Empty, childBoundNodes: ImmutableArray<BoundExpression>.Empty, node.Type); return _factory.Sequence(ImmutableArray.Create(handlerTemp.LocalSymbol), handlerPatternExpressions.ToImmutableAndFree(), toStringAndClearCall); } else if (CanLowerToStringConcatenation(node)) { // All fill-ins, if any, are strings, and none of them have alignment or format specifiers. // We can lower to a more efficient string concatenation // The normal pattern for lowering is to lower subtrees before the enclosing tree. However in this case // we want to lower the entire concatenation so we get the optimizations done by that lowering (e.g. constant folding). int length = node.Parts.Length; if (length == 0) { // $"" -> "" return _factory.StringLiteral(""); } result = null; for (int i = 0; i < length; i++) { var part = node.Parts[i]; if (part is BoundStringInsert fillin) { // this is one of the filled-in expressions part = fillin.Value; } else { // this is one of the literal parts Debug.Assert(part is BoundLiteral && part.ConstantValue is { StringValue: { } }); part = _factory.StringLiteral(ConstantValueUtils.UnescapeInterpolatedStringLiteral(part.ConstantValue.StringValue)); } result = result == null ? part : _factory.Binary(BinaryOperatorKind.StringConcatenation, node.Type, result, part); } // We need to ensure that the result of the interpolated string is not null. If the single part has a non-null constant value // or is itself an interpolated string (which by proxy cannot be null), then there's nothing else that needs to be done. Otherwise, // we need to test for null and ensure "" if it is. if (length == 1 && result is not ({ Kind: BoundKind.InterpolatedString } or { ConstantValue: { IsString: true } })) { result = _factory.Coalesce(result!, _factory.StringLiteral("")); } } else { // // We lower an interpolated string into an invocation of String.Format. For example, we translate the expression // // $"Jenny don\'t change your number { 8675309 }" // // into // // String.Format("Jenny don\'t change your number {0}", new object[] { 8675309 }) // MakeInterpolatedStringFormat(node, out BoundExpression format, out ArrayBuilder<BoundExpression> expressions); // The normal pattern for lowering is to lower subtrees before the enclosing tree. However we cannot lower // the arguments first in this situation because we do not know what conversions will be // produced for the arguments until after we've done overload resolution. So we produce the invocation // and then lower it along with its arguments. expressions.Insert(0, format); var stringType = node.Type; result = _factory.StaticCall(stringType, "Format", expressions.ToImmutableAndFree(), allowUnexpandedForm: false // if an interpolation expression is the null literal, it should not match a params parameter. ); } Debug.Assert(result is { }); if (!result.HasAnyErrors) { result = VisitExpression(result); // lower the arguments AND handle expanded form, argument conversions, etc. result = MakeImplicitConversion(result, node.Type); } return result; } [Conditional("DEBUG")] private static void AssertNoImplicitInterpolatedStringHandlerConversions(ImmutableArray<BoundExpression> arguments, bool allowConversionsWithNoContext = false) { if (allowConversionsWithNoContext) { foreach (var arg in arguments) { if (arg is BoundConversion { Conversion: { Kind: ConversionKind.InterpolatedStringHandler }, ExplicitCastInCode: false, Operand: BoundInterpolatedString @string }) { Debug.Assert(((BoundObjectCreationExpression)@string.InterpolationData!.Value.Construction).Arguments.All( a => a is BoundInterpolatedStringArgumentPlaceholder { ArgumentIndex: BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter } or not BoundInterpolatedStringArgumentPlaceholder)); } } } else { Debug.Assert(arguments.All(arg => arg is not BoundConversion { Conversion: { IsInterpolatedStringHandler: true }, ExplicitCastInCode: false })); } } } }
// 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using System.Diagnostics; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { private BoundExpression RewriteInterpolatedStringConversion(BoundConversion conversion) { Debug.Assert(conversion.ConversionKind == ConversionKind.InterpolatedString); BoundExpression format; ArrayBuilder<BoundExpression> expressions; MakeInterpolatedStringFormat((BoundInterpolatedString)conversion.Operand, out format, out expressions); expressions.Insert(0, format); var stringFactory = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory); // The normal pattern for lowering is to lower subtrees before the enclosing tree. However we cannot lower // the arguments first in this situation because we do not know what conversions will be // produced for the arguments until after we've done overload resolution. So we produce the invocation // and then lower it along with its arguments. var result = _factory.StaticCall(stringFactory, "Create", expressions.ToImmutableAndFree(), allowUnexpandedForm: false // if an interpolation expression is the null literal, it should not match a params parameter. ); if (!result.HasAnyErrors) { result = VisitExpression(result); // lower the arguments AND handle expanded form, argument conversions, etc. result = MakeImplicitConversion(result, conversion.Type); } return result; } /// <summary> /// Rewrites the given interpolated string to the set of handler creation and Append calls, returning an array builder of the append calls and the result /// local temp. /// </summary> /// <remarks>Caller is responsible for freeing the ArrayBuilder</remarks> private (ArrayBuilder<BoundExpression> HandlerPatternExpressions, BoundLocal Result) RewriteToInterpolatedStringHandlerPattern(BoundInterpolatedString node) { Debug.Assert(node.InterpolationData is { Construction: not null }); Debug.Assert(node.Parts.All(static p => p is BoundCall or BoundDynamicInvocation or BoundDynamicMemberAccess or BoundDynamicIndexerAccess)); var data = node.InterpolationData.Value; var builderTempSymbol = _factory.InterpolatedStringHandlerLocal(data.BuilderType, data.ScopeOfContainingExpression, node.Syntax); BoundLocal builderTemp = _factory.Local(builderTempSymbol); // var handler = new HandlerType(baseStringLength, numFormatHoles, ...InterpolatedStringHandlerArgumentAttribute parameters, <optional> out bool appendShouldProceed); var construction = (BoundObjectCreationExpression)data.Construction; BoundLocal? appendShouldProceedLocal = null; if (data.HasTrailingHandlerValidityParameter) { Debug.Assert(construction.ArgumentRefKindsOpt[^1] == RefKind.Out); BoundInterpolatedStringArgumentPlaceholder trailingParameter = data.ArgumentPlaceholders[^1]; TypeSymbol localType = trailingParameter.Type; Debug.Assert(localType.SpecialType == SpecialType.System_Boolean); var outLocal = _factory.SynthesizedLocal(localType); appendShouldProceedLocal = _factory.Local(outLocal); AddPlaceholderReplacement(trailingParameter, appendShouldProceedLocal); } var handlerConstructionAssignment = _factory.AssignmentExpression(builderTemp, (BoundExpression)VisitObjectCreationExpression(construction)); AddPlaceholderReplacement(data.ReceiverPlaceholder, builderTemp); bool usesBoolReturns = data.UsesBoolReturns; var resultExpressions = ArrayBuilder<BoundExpression>.GetInstance(node.Parts.Length + 1); foreach (var part in node.Parts) { if (part is BoundCall call) { Debug.Assert(call.Type.SpecialType == SpecialType.System_Boolean == usesBoolReturns); resultExpressions.Add((BoundExpression)VisitCall(call)); } else if (part is BoundDynamicInvocation dynamicInvocation) { resultExpressions.Add(VisitDynamicInvocation(dynamicInvocation, resultDiscarded: !usesBoolReturns)); } else { throw ExceptionUtilities.UnexpectedValue(part.Kind); } } RemovePlaceholderReplacement(data.ReceiverPlaceholder); if (appendShouldProceedLocal is not null) { RemovePlaceholderReplacement(data.ArgumentPlaceholders[^1]); } if (usesBoolReturns) { // We assume non-bool returns if there was no parts to the string, and code below is predicated on that. Debug.Assert(!node.Parts.IsEmpty); // Start the sequence with appendProceedLocal, if appropriate BoundExpression? currentExpression = appendShouldProceedLocal; var boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); foreach (var appendCall in resultExpressions) { var actualCall = appendCall; if (actualCall.Type!.IsDynamic()) { actualCall = _dynamicFactory.MakeDynamicConversion(actualCall, isExplicit: false, isArrayIndex: false, isChecked: false, boolType).ToExpression(); } // previousAppendCalls && appendCall currentExpression = currentExpression is null ? actualCall : _factory.LogicalAnd(currentExpression, actualCall); } resultExpressions.Clear(); Debug.Assert(currentExpression != null); var sequence = _factory.Sequence( appendShouldProceedLocal is not null ? ImmutableArray.Create(appendShouldProceedLocal.LocalSymbol) : ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create<BoundExpression>(handlerConstructionAssignment), currentExpression); resultExpressions.Add(sequence); } else if (appendShouldProceedLocal is not null && resultExpressions.Count > 0) { // appendCalls Sequence ending in true var appendCallsSequence = _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, resultExpressions.ToImmutableAndClear(), _factory.Literal(value: true)); resultExpressions.Add(handlerConstructionAssignment); // appendShouldProceedLocal && sequence var appendAnd = _factory.LogicalAnd(appendShouldProceedLocal, appendCallsSequence); var result = _factory.Sequence(ImmutableArray.Create(appendShouldProceedLocal.LocalSymbol), resultExpressions.ToImmutableAndClear(), appendAnd); resultExpressions.Add(result); } else if (appendShouldProceedLocal is not null) { // Odd case of no append calls, but with an out param. We don't need to generate any jumps checking the local because there's // nothing to short circuit and avoid, but we do need a sequence to hold the lifetime of the local resultExpressions.Add(_factory.Sequence(ImmutableArray.Create(appendShouldProceedLocal.LocalSymbol), ImmutableArray<BoundExpression>.Empty, handlerConstructionAssignment)); } else { resultExpressions.Insert(0, handlerConstructionAssignment); } return (resultExpressions, builderTemp); } private bool CanLowerToStringConcatenation(BoundInterpolatedString node) { foreach (var part in node.Parts) { if (part is BoundStringInsert fillin) { // this is one of the expression holes if (_inExpressionLambda || fillin.HasErrors || fillin.Value.Type?.SpecialType != SpecialType.System_String || fillin.Alignment != null || fillin.Format != null) { return false; } } } return true; } private void MakeInterpolatedStringFormat(BoundInterpolatedString node, out BoundExpression format, out ArrayBuilder<BoundExpression> expressions) { _factory.Syntax = node.Syntax; int n = node.Parts.Length - 1; var formatString = PooledStringBuilder.GetInstance(); var stringBuilder = formatString.Builder; expressions = ArrayBuilder<BoundExpression>.GetInstance(n + 1); int nextFormatPosition = 0; for (int i = 0; i <= n; i++) { var part = node.Parts[i]; var fillin = part as BoundStringInsert; if (fillin == null) { Debug.Assert(part is BoundLiteral && part.ConstantValue != null); // this is one of the literal parts stringBuilder.Append(part.ConstantValue.StringValue); } else { // this is one of the expression holes stringBuilder.Append('{').Append(nextFormatPosition++); if (fillin.Alignment != null && !fillin.Alignment.HasErrors) { Debug.Assert(fillin.Alignment.ConstantValue is { }); stringBuilder.Append(',').Append(fillin.Alignment.ConstantValue.Int64Value); } if (fillin.Format != null && !fillin.Format.HasErrors) { Debug.Assert(fillin.Format.ConstantValue is { }); stringBuilder.Append(':').Append(fillin.Format.ConstantValue.StringValue); } stringBuilder.Append('}'); var value = fillin.Value; if (value.Type?.TypeKind == TypeKind.Dynamic) { value = MakeConversionNode(value, _compilation.ObjectType, @checked: false); } expressions.Add(value); // NOTE: must still be lowered } } format = _factory.StringLiteral(formatString.ToStringAndFree()); } public override BoundNode VisitInterpolatedString(BoundInterpolatedString node) { Debug.Assert(node.Type is { SpecialType: SpecialType.System_String }); // if target-converted, we should not get here. BoundExpression? result; if (node.InterpolationData is not null) { // If we can lower to the builder pattern, do so. (ArrayBuilder<BoundExpression> handlerPatternExpressions, BoundLocal handlerTemp) = RewriteToInterpolatedStringHandlerPattern(node); // resultTemp = builderTemp.ToStringAndClear(); var toStringAndClear = (MethodSymbol)Binder.GetWellKnownTypeMember(_compilation, WellKnownMember.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear, _diagnostics, syntax: node.Syntax); BoundExpression toStringAndClearCall = toStringAndClear is not null ? BoundCall.Synthesized(node.Syntax, handlerTemp, toStringAndClear) : new BoundBadExpression(node.Syntax, LookupResultKind.Empty, symbols: ImmutableArray<Symbol?>.Empty, childBoundNodes: ImmutableArray<BoundExpression>.Empty, node.Type); return _factory.Sequence(ImmutableArray.Create(handlerTemp.LocalSymbol), handlerPatternExpressions.ToImmutableAndFree(), toStringAndClearCall); } else if (CanLowerToStringConcatenation(node)) { // All fill-ins, if any, are strings, and none of them have alignment or format specifiers. // We can lower to a more efficient string concatenation // The normal pattern for lowering is to lower subtrees before the enclosing tree. However in this case // we want to lower the entire concatenation so we get the optimizations done by that lowering (e.g. constant folding). int length = node.Parts.Length; if (length == 0) { // $"" -> "" return _factory.StringLiteral(""); } result = null; for (int i = 0; i < length; i++) { var part = node.Parts[i]; if (part is BoundStringInsert fillin) { // this is one of the filled-in expressions part = fillin.Value; } else { // this is one of the literal parts Debug.Assert(part is BoundLiteral && part.ConstantValue is { StringValue: { } }); part = _factory.StringLiteral(ConstantValueUtils.UnescapeInterpolatedStringLiteral(part.ConstantValue.StringValue)); } result = result == null ? part : _factory.Binary(BinaryOperatorKind.StringConcatenation, node.Type, result, part); } // We need to ensure that the result of the interpolated string is not null. If the single part has a non-null constant value // or is itself an interpolated string (which by proxy cannot be null), then there's nothing else that needs to be done. Otherwise, // we need to test for null and ensure "" if it is. if (length == 1 && result is not ({ Kind: BoundKind.InterpolatedString } or { ConstantValue: { IsString: true } })) { result = _factory.Coalesce(result!, _factory.StringLiteral("")); } } else { // // We lower an interpolated string into an invocation of String.Format. For example, we translate the expression // // $"Jenny don\'t change your number { 8675309 }" // // into // // String.Format("Jenny don\'t change your number {0}", new object[] { 8675309 }) // MakeInterpolatedStringFormat(node, out BoundExpression format, out ArrayBuilder<BoundExpression> expressions); // The normal pattern for lowering is to lower subtrees before the enclosing tree. However we cannot lower // the arguments first in this situation because we do not know what conversions will be // produced for the arguments until after we've done overload resolution. So we produce the invocation // and then lower it along with its arguments. expressions.Insert(0, format); var stringType = node.Type; result = _factory.StaticCall(stringType, "Format", expressions.ToImmutableAndFree(), allowUnexpandedForm: false // if an interpolation expression is the null literal, it should not match a params parameter. ); } Debug.Assert(result is { }); if (!result.HasAnyErrors) { result = VisitExpression(result); // lower the arguments AND handle expanded form, argument conversions, etc. result = MakeImplicitConversion(result, node.Type); } return result; } [Conditional("DEBUG")] private static void AssertNoImplicitInterpolatedStringHandlerConversions(ImmutableArray<BoundExpression> arguments, bool allowConversionsWithNoContext = false) { if (allowConversionsWithNoContext) { foreach (var arg in arguments) { if (arg is BoundConversion { Conversion: { Kind: ConversionKind.InterpolatedStringHandler }, ExplicitCastInCode: false, Operand: BoundInterpolatedString @string }) { Debug.Assert(((BoundObjectCreationExpression)@string.InterpolationData!.Value.Construction).Arguments.All( a => a is BoundInterpolatedStringArgumentPlaceholder { ArgumentIndex: BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter } or not BoundInterpolatedStringArgumentPlaceholder)); } } } else { Debug.Assert(arguments.All(arg => arg is not BoundConversion { Conversion: { IsInterpolatedStringHandler: true }, ExplicitCastInCode: false })); } } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Portable/Compilation/LexicalOrderSymbolComparer.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 Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This is an implementation of a special symbol comparer, which is supposed to be used for ''' sorting original definition symbols (explicitly or explicitly declared in source within the same ''' container) in lexical order of their declarations. It will not work on anything that uses non-source locations. ''' </summary> Friend Class LexicalOrderSymbolComparer Implements IComparer(Of Symbol) Public Shared ReadOnly Instance As New LexicalOrderSymbolComparer() Private Sub New() End Sub Public Function Compare(x As Symbol, y As Symbol) As Integer Implements IComparer(Of Symbol).Compare Dim comparison As Integer If x Is y Then Return 0 End If Dim xSortKey = x.GetLexicalSortKey() Dim ySortKey = y.GetLexicalSortKey() comparison = LexicalSortKey.Compare(xSortKey, ySortKey) If comparison <> 0 Then Return comparison End If comparison = DirectCast(x, ISymbol).Kind.ToSortOrder() - DirectCast(y, ISymbol).Kind.ToSortOrder() If comparison <> 0 Then Return comparison End If comparison = IdentifierComparison.Compare(x.Name, y.Name) Debug.Assert(comparison <> 0) Return comparison 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 Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This is an implementation of a special symbol comparer, which is supposed to be used for ''' sorting original definition symbols (explicitly or explicitly declared in source within the same ''' container) in lexical order of their declarations. It will not work on anything that uses non-source locations. ''' </summary> Friend Class LexicalOrderSymbolComparer Implements IComparer(Of Symbol) Public Shared ReadOnly Instance As New LexicalOrderSymbolComparer() Private Sub New() End Sub Public Function Compare(x As Symbol, y As Symbol) As Integer Implements IComparer(Of Symbol).Compare Dim comparison As Integer If x Is y Then Return 0 End If Dim xSortKey = x.GetLexicalSortKey() Dim ySortKey = y.GetLexicalSortKey() comparison = LexicalSortKey.Compare(xSortKey, ySortKey) If comparison <> 0 Then Return comparison End If comparison = DirectCast(x, ISymbol).Kind.ToSortOrder() - DirectCast(y, ISymbol).Kind.ToSortOrder() If comparison <> 0 Then Return comparison End If comparison = IdentifierComparison.Compare(x.Name, y.Name) Debug.Assert(comparison <> 0) Return comparison End Function End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodOrUserDefinedOperatorSymbol.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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceOrdinaryMethodOrUserDefinedOperatorSymbol : SourceMemberMethodSymbol { private ImmutableArray<MethodSymbol> _lazyExplicitInterfaceImplementations; private ImmutableArray<CustomModifier> _lazyRefCustomModifiers; private ImmutableArray<ParameterSymbol> _lazyParameters; private TypeWithAnnotations _lazyReturnType; protected SourceOrdinaryMethodOrUserDefinedOperatorSymbol(NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, Location location, bool isIterator) : base(containingType, syntaxReferenceOpt, location, isIterator) { } protected abstract Location ReturnTypeLocation { get; } public sealed override bool ReturnsVoid { get { LazyMethodChecks(); return base.ReturnsVoid; } } protected MethodSymbol? MethodChecks(TypeWithAnnotations returnType, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics) { _lazyReturnType = returnType; _lazyParameters = parameters; // set ReturnsVoid flag this.SetReturnsVoid(_lazyReturnType.IsVoidType()); this.CheckEffectiveAccessibility(_lazyReturnType, _lazyParameters, diagnostics); var location = locations[0]; // Checks taken from MemberDefiner::defineMethod if (this.Name == WellKnownMemberNames.DestructorName && this.ParameterCount == 0 && this.Arity == 0 && this.ReturnsVoid) { diagnostics.Add(ErrorCode.WRN_FinalizeMethod, location); } ExtensionMethodChecks(diagnostics); if (IsPartial) { if (MethodKind == MethodKind.ExplicitInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_PartialMethodNotExplicit, location); } if (!ContainingType.IsPartial()) { diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyInPartialClass, location); } } if (!IsPartial) { LazyAsyncMethodChecks(CancellationToken.None); Debug.Assert(state.HasComplete(CompletionPart.FinishAsyncMethodChecks)); } // The runtime will not treat this method as an override or implementation of another // method unless both the signatures and the custom modifiers match. Hence, in the // case of overrides and *explicit* implementations, we need to copy the custom modifiers // that are in the signature of the overridden/implemented method. (From source, we know // that there can only be one such method, so there are no conflicts.) This is // unnecessary for implicit implementations because, if the custom modifiers don't match, // we'll insert a bridge method (an explicit implementation that delegates to the implicit // implementation) with the correct custom modifiers // (see SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation). // This value may not be correct, but we need something while we compute this.OverriddenMethod. // May be re-assigned below. Debug.Assert(_lazyReturnType.CustomModifiers.IsEmpty); _lazyRefCustomModifiers = ImmutableArray<CustomModifier>.Empty; MethodSymbol? overriddenOrExplicitlyImplementedMethod = null; // Note: we're checking if the syntax indicates explicit implementation rather, // than if explicitInterfaceType is null because we don't want to look for an // overridden property if this is supposed to be an explicit implementation. if (MethodKind != MethodKind.ExplicitInterfaceImplementation) { Debug.Assert(_lazyExplicitInterfaceImplementations.IsDefault); _lazyExplicitInterfaceImplementations = ImmutableArray<MethodSymbol>.Empty; // If this method is an override, we may need to copy custom modifiers from // the overridden method (so that the runtime will recognize it as an override). // We check for this case here, while we can still modify the parameters and // return type without losing the appearance of immutability. if (this.IsOverride) { // This computation will necessarily be performed with partially incomplete // information. There is no way we can determine the complete signature // (i.e. including custom modifiers) until we have found the method that // this method overrides. To accommodate this, MethodSymbol.OverriddenOrHiddenMembers // is written to allow relaxed matching of custom modifiers for source methods, // on the assumption that they will be updated appropriately. overriddenOrExplicitlyImplementedMethod = this.OverriddenMethod; if ((object)overriddenOrExplicitlyImplementedMethod != null) { CustomModifierUtils.CopyMethodCustomModifiers(overriddenOrExplicitlyImplementedMethod, this, out _lazyReturnType, out _lazyRefCustomModifiers, out _lazyParameters, alsoCopyParamsModifier: true); } } else if (RefKind == RefKind.RefReadOnly) { var modifierType = Binder.GetWellKnownType(DeclaringCompilation, WellKnownType.System_Runtime_InteropServices_InAttribute, diagnostics, ReturnTypeLocation); _lazyRefCustomModifiers = ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType)); } } else if (ExplicitInterfaceType is not null) { //do this last so that it can assume the method symbol is constructed (except for ExplicitInterfaceImplementation) overriddenOrExplicitlyImplementedMethod = FindExplicitlyImplementedMethod(diagnostics); if (overriddenOrExplicitlyImplementedMethod is not null) { Debug.Assert(_lazyExplicitInterfaceImplementations.IsDefault); _lazyExplicitInterfaceImplementations = ImmutableArray.Create<MethodSymbol>(overriddenOrExplicitlyImplementedMethod); CustomModifierUtils.CopyMethodCustomModifiers(overriddenOrExplicitlyImplementedMethod, this, out _lazyReturnType, out _lazyRefCustomModifiers, out _lazyParameters, alsoCopyParamsModifier: false); this.FindExplicitlyImplementedMemberVerification(overriddenOrExplicitlyImplementedMethod, diagnostics); TypeSymbol.CheckNullableReferenceTypeMismatchOnImplementingMember(this.ContainingType, this, overriddenOrExplicitlyImplementedMethod, isExplicit: true, diagnostics); } else { Debug.Assert(_lazyExplicitInterfaceImplementations.IsDefault); _lazyExplicitInterfaceImplementations = ImmutableArray<MethodSymbol>.Empty; Debug.Assert(_lazyReturnType.CustomModifiers.IsEmpty); } } return overriddenOrExplicitlyImplementedMethod; } protected abstract void ExtensionMethodChecks(BindingDiagnosticBag diagnostics); protected abstract MethodSymbol? FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics); protected abstract TypeSymbol? ExplicitInterfaceType { get; } internal sealed override int ParameterCount { get { if (!_lazyParameters.IsDefault) { int result = _lazyParameters.Length; Debug.Assert(result == GetParameterCountFromSyntax()); return result; } return GetParameterCountFromSyntax(); } } protected abstract int GetParameterCountFromSyntax(); public sealed override ImmutableArray<ParameterSymbol> Parameters { get { LazyMethodChecks(); return _lazyParameters; } } public sealed override TypeWithAnnotations ReturnTypeWithAnnotations { get { LazyMethodChecks(); return _lazyReturnType; } } internal sealed override bool IsExplicitInterfaceImplementation { get { return MethodKind == MethodKind.ExplicitInterfaceImplementation; } } public sealed override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { LazyMethodChecks(); return _lazyExplicitInterfaceImplementations; } } public sealed override ImmutableArray<CustomModifier> RefCustomModifiers { get { LazyMethodChecks(); return _lazyRefCustomModifiers; } } internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { base.AfterAddingTypeMembersChecks(conversions, diagnostics); var location = ReturnTypeLocation; var compilation = DeclaringCompilation; Debug.Assert(location != null); // Check constraints on return type and parameters. Note: Dev10 uses the // method name location for any such errors. We'll do the same for return // type errors but for parameter errors, we'll use the parameter location. CheckConstraintsForExplicitInterfaceType(conversions, diagnostics); this.ReturnType.CheckAllConstraints(compilation, conversions, this.Locations[0], diagnostics); foreach (var parameter in this.Parameters) { parameter.Type.CheckAllConstraints(compilation, conversions, parameter.Locations[0], diagnostics); } PartialMethodChecks(diagnostics); if (RefKind == RefKind.RefReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } ParameterHelpers.EnsureIsReadOnlyAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true); if (ReturnType.ContainsNativeInteger()) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true); } ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true); if (compilation.ShouldEmitNullableAttributes(this) && ReturnTypeWithAnnotations.NeedsNullableAttribute()) { compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true); } ParameterHelpers.EnsureNullableAttributeExists(compilation, this, Parameters, diagnostics, modifyCompilation: true); } protected abstract void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics); protected abstract void PartialMethodChecks(BindingDiagnosticBag diagnostics); } }
// 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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceOrdinaryMethodOrUserDefinedOperatorSymbol : SourceMemberMethodSymbol { private ImmutableArray<MethodSymbol> _lazyExplicitInterfaceImplementations; private ImmutableArray<CustomModifier> _lazyRefCustomModifiers; private ImmutableArray<ParameterSymbol> _lazyParameters; private TypeWithAnnotations _lazyReturnType; protected SourceOrdinaryMethodOrUserDefinedOperatorSymbol(NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, Location location, bool isIterator) : base(containingType, syntaxReferenceOpt, location, isIterator) { } protected abstract Location ReturnTypeLocation { get; } public sealed override bool ReturnsVoid { get { LazyMethodChecks(); return base.ReturnsVoid; } } protected MethodSymbol? MethodChecks(TypeWithAnnotations returnType, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics) { _lazyReturnType = returnType; _lazyParameters = parameters; // set ReturnsVoid flag this.SetReturnsVoid(_lazyReturnType.IsVoidType()); this.CheckEffectiveAccessibility(_lazyReturnType, _lazyParameters, diagnostics); var location = locations[0]; // Checks taken from MemberDefiner::defineMethod if (this.Name == WellKnownMemberNames.DestructorName && this.ParameterCount == 0 && this.Arity == 0 && this.ReturnsVoid) { diagnostics.Add(ErrorCode.WRN_FinalizeMethod, location); } ExtensionMethodChecks(diagnostics); if (IsPartial) { if (MethodKind == MethodKind.ExplicitInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_PartialMethodNotExplicit, location); } if (!ContainingType.IsPartial()) { diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyInPartialClass, location); } } if (!IsPartial) { LazyAsyncMethodChecks(CancellationToken.None); Debug.Assert(state.HasComplete(CompletionPart.FinishAsyncMethodChecks)); } // The runtime will not treat this method as an override or implementation of another // method unless both the signatures and the custom modifiers match. Hence, in the // case of overrides and *explicit* implementations, we need to copy the custom modifiers // that are in the signature of the overridden/implemented method. (From source, we know // that there can only be one such method, so there are no conflicts.) This is // unnecessary for implicit implementations because, if the custom modifiers don't match, // we'll insert a bridge method (an explicit implementation that delegates to the implicit // implementation) with the correct custom modifiers // (see SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation). // This value may not be correct, but we need something while we compute this.OverriddenMethod. // May be re-assigned below. Debug.Assert(_lazyReturnType.CustomModifiers.IsEmpty); _lazyRefCustomModifiers = ImmutableArray<CustomModifier>.Empty; MethodSymbol? overriddenOrExplicitlyImplementedMethod = null; // Note: we're checking if the syntax indicates explicit implementation rather, // than if explicitInterfaceType is null because we don't want to look for an // overridden property if this is supposed to be an explicit implementation. if (MethodKind != MethodKind.ExplicitInterfaceImplementation) { Debug.Assert(_lazyExplicitInterfaceImplementations.IsDefault); _lazyExplicitInterfaceImplementations = ImmutableArray<MethodSymbol>.Empty; // If this method is an override, we may need to copy custom modifiers from // the overridden method (so that the runtime will recognize it as an override). // We check for this case here, while we can still modify the parameters and // return type without losing the appearance of immutability. if (this.IsOverride) { // This computation will necessarily be performed with partially incomplete // information. There is no way we can determine the complete signature // (i.e. including custom modifiers) until we have found the method that // this method overrides. To accommodate this, MethodSymbol.OverriddenOrHiddenMembers // is written to allow relaxed matching of custom modifiers for source methods, // on the assumption that they will be updated appropriately. overriddenOrExplicitlyImplementedMethod = this.OverriddenMethod; if ((object)overriddenOrExplicitlyImplementedMethod != null) { CustomModifierUtils.CopyMethodCustomModifiers(overriddenOrExplicitlyImplementedMethod, this, out _lazyReturnType, out _lazyRefCustomModifiers, out _lazyParameters, alsoCopyParamsModifier: true); } } else if (RefKind == RefKind.RefReadOnly) { var modifierType = Binder.GetWellKnownType(DeclaringCompilation, WellKnownType.System_Runtime_InteropServices_InAttribute, diagnostics, ReturnTypeLocation); _lazyRefCustomModifiers = ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType)); } } else if (ExplicitInterfaceType is not null) { //do this last so that it can assume the method symbol is constructed (except for ExplicitInterfaceImplementation) overriddenOrExplicitlyImplementedMethod = FindExplicitlyImplementedMethod(diagnostics); if (overriddenOrExplicitlyImplementedMethod is not null) { Debug.Assert(_lazyExplicitInterfaceImplementations.IsDefault); _lazyExplicitInterfaceImplementations = ImmutableArray.Create<MethodSymbol>(overriddenOrExplicitlyImplementedMethod); CustomModifierUtils.CopyMethodCustomModifiers(overriddenOrExplicitlyImplementedMethod, this, out _lazyReturnType, out _lazyRefCustomModifiers, out _lazyParameters, alsoCopyParamsModifier: false); this.FindExplicitlyImplementedMemberVerification(overriddenOrExplicitlyImplementedMethod, diagnostics); TypeSymbol.CheckNullableReferenceTypeMismatchOnImplementingMember(this.ContainingType, this, overriddenOrExplicitlyImplementedMethod, isExplicit: true, diagnostics); } else { Debug.Assert(_lazyExplicitInterfaceImplementations.IsDefault); _lazyExplicitInterfaceImplementations = ImmutableArray<MethodSymbol>.Empty; Debug.Assert(_lazyReturnType.CustomModifiers.IsEmpty); } } return overriddenOrExplicitlyImplementedMethod; } protected abstract void ExtensionMethodChecks(BindingDiagnosticBag diagnostics); protected abstract MethodSymbol? FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics); protected abstract TypeSymbol? ExplicitInterfaceType { get; } internal sealed override int ParameterCount { get { if (!_lazyParameters.IsDefault) { int result = _lazyParameters.Length; Debug.Assert(result == GetParameterCountFromSyntax()); return result; } return GetParameterCountFromSyntax(); } } protected abstract int GetParameterCountFromSyntax(); public sealed override ImmutableArray<ParameterSymbol> Parameters { get { LazyMethodChecks(); return _lazyParameters; } } public sealed override TypeWithAnnotations ReturnTypeWithAnnotations { get { LazyMethodChecks(); return _lazyReturnType; } } internal sealed override bool IsExplicitInterfaceImplementation { get { return MethodKind == MethodKind.ExplicitInterfaceImplementation; } } public sealed override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { LazyMethodChecks(); return _lazyExplicitInterfaceImplementations; } } public sealed override ImmutableArray<CustomModifier> RefCustomModifiers { get { LazyMethodChecks(); return _lazyRefCustomModifiers; } } internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { base.AfterAddingTypeMembersChecks(conversions, diagnostics); var location = ReturnTypeLocation; var compilation = DeclaringCompilation; Debug.Assert(location != null); // Check constraints on return type and parameters. Note: Dev10 uses the // method name location for any such errors. We'll do the same for return // type errors but for parameter errors, we'll use the parameter location. CheckConstraintsForExplicitInterfaceType(conversions, diagnostics); this.ReturnType.CheckAllConstraints(compilation, conversions, this.Locations[0], diagnostics); foreach (var parameter in this.Parameters) { parameter.Type.CheckAllConstraints(compilation, conversions, parameter.Locations[0], diagnostics); } PartialMethodChecks(diagnostics); if (RefKind == RefKind.RefReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } ParameterHelpers.EnsureIsReadOnlyAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true); if (ReturnType.ContainsNativeInteger()) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true); } ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true); if (compilation.ShouldEmitNullableAttributes(this) && ReturnTypeWithAnnotations.NeedsNullableAttribute()) { compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true); } ParameterHelpers.EnsureNullableAttributeExists(compilation, this, Parameters, diagnostics, modifyCompilation: true); } protected abstract void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics); protected abstract void PartialMethodChecks(BindingDiagnosticBag diagnostics); } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/VenusMargin/ProjectionSpanTag.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.VisualStudio.Text.Tagging; namespace Roslyn.Hosting.Diagnostics.VenusMargin { internal class ProjectionSpanTag : TextMarkerTag { public const string TagId = "ProjectionTag"; public static readonly ProjectionSpanTag Instance = new ProjectionSpanTag(); public ProjectionSpanTag() : base(TagId) { } } }
// 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.VisualStudio.Text.Tagging; namespace Roslyn.Hosting.Diagnostics.VenusMargin { internal class ProjectionSpanTag : TextMarkerTag { public const string TagId = "ProjectionTag"; public static readonly ProjectionSpanTag Instance = new ProjectionSpanTag(); public ProjectionSpanTag() : base(TagId) { } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Core/Portable/VersionHelper.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 System.Globalization; namespace Microsoft.CodeAnalysis { internal static class VersionHelper { /// <summary> /// Parses a version string of the form "major [ '.' minor [ '.' build [ '.' revision ] ] ]". /// </summary> /// <param name="s">The version string to parse.</param> /// <param name="version">If parsing succeeds, the parsed version. Otherwise a version that represents as much of the input as could be parsed successfully.</param> /// <returns>True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise.</returns> internal static bool TryParse(string s, out Version version) { return TryParse(s, allowWildcard: false, maxValue: ushort.MaxValue, allowPartialParse: true, version: out version); } /// <summary> /// Parses a version string of the form "major [ '.' minor [ '.' ( '*' | ( build [ '.' ( '*' | revision ) ] ) ) ] ]" /// as accepted by System.Reflection.AssemblyVersionAttribute. /// </summary> /// <param name="s">The version string to parse.</param> /// <param name="allowWildcard">Indicates whether or not a wildcard is accepted as the terminal component.</param> /// <param name="version"> /// If parsing succeeded, the parsed version. Otherwise a version instance with all parts set to zero. /// If <paramref name="s"/> contains * the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>. /// </param> /// <returns>True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise.</returns> internal static bool TryParseAssemblyVersion(string s, bool allowWildcard, out Version version) { return TryParse(s, allowWildcard: allowWildcard, maxValue: ushort.MaxValue - 1, allowPartialParse: false, version: out version); } /// <summary> /// Parses a version string of the form "major [ '.' minor [ '.' ( '*' | ( build [ '.' ( '*' | revision ) ] ) ) ] ]" /// as accepted by System.Reflection.AssemblyVersionAttribute. /// </summary> /// <param name="s">The version string to parse.</param> /// <param name="allowWildcard">Indicates whether or not we're parsing an assembly version string. If so, wildcards are accepted and each component must be less than 65535.</param> /// <param name="maxValue">The maximum value that a version component may have.</param> /// <param name="allowPartialParse">Allow the parsing of version elements where invalid characters exist. e.g. 1.2.2a.1</param> /// <param name="version"> /// If parsing succeeded, the parsed version. When <paramref name="allowPartialParse"/> is true a version with values up to the first invalid character set. Otherwise a version with all parts set to zero. /// If <paramref name="s"/> contains * and wildcard is allowed the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>. /// </param> /// <returns>True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise.</returns> private static bool TryParse(string s, bool allowWildcard, ushort maxValue, bool allowPartialParse, out Version version) { Debug.Assert(!allowWildcard || maxValue < ushort.MaxValue); if (string.IsNullOrWhiteSpace(s)) { version = AssemblyIdentity.NullVersion; return false; } string[] elements = s.Split('.'); // If the wildcard is being used, the first two elements must be specified explicitly, and // the last must be a exactly single asterisk without whitespace. bool hasWildcard = allowWildcard && elements[elements.Length - 1] == "*"; if ((hasWildcard && elements.Length < 3) || elements.Length > 4) { version = AssemblyIdentity.NullVersion; return false; } ushort[] values = new ushort[4]; int lastExplicitValue = hasWildcard ? elements.Length - 1 : elements.Length; bool parseError = false; for (int i = 0; i < lastExplicitValue; i++) { if (!ushort.TryParse(elements[i], NumberStyles.None, CultureInfo.InvariantCulture, out values[i]) || values[i] > maxValue) { if (!allowPartialParse) { version = AssemblyIdentity.NullVersion; return false; } parseError = true; if (string.IsNullOrWhiteSpace(elements[i])) { values[i] = 0; break; } if (values[i] > maxValue) { //The only way this can happen is if the value was 65536 //The old compiler would continue parsing from here values[i] = 0; continue; } bool invalidFormat = false; System.Numerics.BigInteger number = 0; //There could be an invalid character in the input so check for the presence of one and //parse up to that point. examples of invalid characters are alphas and punctuation for (var idx = 0; idx < elements[i].Length; idx++) { if (!char.IsDigit(elements[i][idx])) { invalidFormat = true; TryGetValue(elements[i].Substring(0, idx), out values[i]); break; } } if (!invalidFormat) { //if we made it here then there weren't any alpha or punctuation chars in the input so the //element is either greater than ushort.MaxValue or possibly a fullwidth unicode digit. if (TryGetValue(elements[i], out values[i])) { //For this scenario the old compiler would continue processing the remaining version elements //so continue processing continue; } } //Don't process any more of the version elements break; } } if (hasWildcard) { for (int i = lastExplicitValue; i < values.Length; i++) { values[i] = ushort.MaxValue; } } version = new Version(values[0], values[1], values[2], values[3]); return !parseError; } private static bool TryGetValue(string s, out ushort value) { System.Numerics.BigInteger number; if (System.Numerics.BigInteger.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out number)) { //The old compiler would take the 16 least significant bits and use their value as the output //so we'll do that too. value = (ushort)(number % 65536); return true; } //One case that will cause us to end up here is when the input is a Fullwidth unicode digit //so we'll always return zero value = 0; return false; } /// <summary> /// If build and/or revision numbers are 65535 they are replaced with time-based values. /// </summary> public static Version? GenerateVersionFromPatternAndCurrentTime(DateTime time, Version pattern) { if (pattern == null || pattern.Revision != ushort.MaxValue) { return pattern; } // MSDN doc on the attribute: // "The default build number increments daily. The default revision number is the number of seconds since midnight local time // (without taking into account time zone adjustments for daylight saving time), divided by 2." if (time == default(DateTime)) { time = DateTime.Now; } int revision = (int)time.TimeOfDay.TotalSeconds / 2; // 24 * 60 * 60 / 2 = 43200 < 65535 Debug.Assert(revision < ushort.MaxValue); if (pattern.Build == ushort.MaxValue) { TimeSpan days = time.Date - new DateTime(2000, 1, 1); int build = Math.Min(ushort.MaxValue, (int)days.TotalDays); return new Version(pattern.Major, pattern.Minor, (ushort)build, (ushort)revision); } else { return new Version(pattern.Major, pattern.Minor, pattern.Build, (ushort)revision); } } } }
// 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 System.Globalization; namespace Microsoft.CodeAnalysis { internal static class VersionHelper { /// <summary> /// Parses a version string of the form "major [ '.' minor [ '.' build [ '.' revision ] ] ]". /// </summary> /// <param name="s">The version string to parse.</param> /// <param name="version">If parsing succeeds, the parsed version. Otherwise a version that represents as much of the input as could be parsed successfully.</param> /// <returns>True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise.</returns> internal static bool TryParse(string s, out Version version) { return TryParse(s, allowWildcard: false, maxValue: ushort.MaxValue, allowPartialParse: true, version: out version); } /// <summary> /// Parses a version string of the form "major [ '.' minor [ '.' ( '*' | ( build [ '.' ( '*' | revision ) ] ) ) ] ]" /// as accepted by System.Reflection.AssemblyVersionAttribute. /// </summary> /// <param name="s">The version string to parse.</param> /// <param name="allowWildcard">Indicates whether or not a wildcard is accepted as the terminal component.</param> /// <param name="version"> /// If parsing succeeded, the parsed version. Otherwise a version instance with all parts set to zero. /// If <paramref name="s"/> contains * the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>. /// </param> /// <returns>True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise.</returns> internal static bool TryParseAssemblyVersion(string s, bool allowWildcard, out Version version) { return TryParse(s, allowWildcard: allowWildcard, maxValue: ushort.MaxValue - 1, allowPartialParse: false, version: out version); } /// <summary> /// Parses a version string of the form "major [ '.' minor [ '.' ( '*' | ( build [ '.' ( '*' | revision ) ] ) ) ] ]" /// as accepted by System.Reflection.AssemblyVersionAttribute. /// </summary> /// <param name="s">The version string to parse.</param> /// <param name="allowWildcard">Indicates whether or not we're parsing an assembly version string. If so, wildcards are accepted and each component must be less than 65535.</param> /// <param name="maxValue">The maximum value that a version component may have.</param> /// <param name="allowPartialParse">Allow the parsing of version elements where invalid characters exist. e.g. 1.2.2a.1</param> /// <param name="version"> /// If parsing succeeded, the parsed version. When <paramref name="allowPartialParse"/> is true a version with values up to the first invalid character set. Otherwise a version with all parts set to zero. /// If <paramref name="s"/> contains * and wildcard is allowed the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>. /// </param> /// <returns>True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise.</returns> private static bool TryParse(string s, bool allowWildcard, ushort maxValue, bool allowPartialParse, out Version version) { Debug.Assert(!allowWildcard || maxValue < ushort.MaxValue); if (string.IsNullOrWhiteSpace(s)) { version = AssemblyIdentity.NullVersion; return false; } string[] elements = s.Split('.'); // If the wildcard is being used, the first two elements must be specified explicitly, and // the last must be a exactly single asterisk without whitespace. bool hasWildcard = allowWildcard && elements[elements.Length - 1] == "*"; if ((hasWildcard && elements.Length < 3) || elements.Length > 4) { version = AssemblyIdentity.NullVersion; return false; } ushort[] values = new ushort[4]; int lastExplicitValue = hasWildcard ? elements.Length - 1 : elements.Length; bool parseError = false; for (int i = 0; i < lastExplicitValue; i++) { if (!ushort.TryParse(elements[i], NumberStyles.None, CultureInfo.InvariantCulture, out values[i]) || values[i] > maxValue) { if (!allowPartialParse) { version = AssemblyIdentity.NullVersion; return false; } parseError = true; if (string.IsNullOrWhiteSpace(elements[i])) { values[i] = 0; break; } if (values[i] > maxValue) { //The only way this can happen is if the value was 65536 //The old compiler would continue parsing from here values[i] = 0; continue; } bool invalidFormat = false; System.Numerics.BigInteger number = 0; //There could be an invalid character in the input so check for the presence of one and //parse up to that point. examples of invalid characters are alphas and punctuation for (var idx = 0; idx < elements[i].Length; idx++) { if (!char.IsDigit(elements[i][idx])) { invalidFormat = true; TryGetValue(elements[i].Substring(0, idx), out values[i]); break; } } if (!invalidFormat) { //if we made it here then there weren't any alpha or punctuation chars in the input so the //element is either greater than ushort.MaxValue or possibly a fullwidth unicode digit. if (TryGetValue(elements[i], out values[i])) { //For this scenario the old compiler would continue processing the remaining version elements //so continue processing continue; } } //Don't process any more of the version elements break; } } if (hasWildcard) { for (int i = lastExplicitValue; i < values.Length; i++) { values[i] = ushort.MaxValue; } } version = new Version(values[0], values[1], values[2], values[3]); return !parseError; } private static bool TryGetValue(string s, out ushort value) { System.Numerics.BigInteger number; if (System.Numerics.BigInteger.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out number)) { //The old compiler would take the 16 least significant bits and use their value as the output //so we'll do that too. value = (ushort)(number % 65536); return true; } //One case that will cause us to end up here is when the input is a Fullwidth unicode digit //so we'll always return zero value = 0; return false; } /// <summary> /// If build and/or revision numbers are 65535 they are replaced with time-based values. /// </summary> public static Version? GenerateVersionFromPatternAndCurrentTime(DateTime time, Version pattern) { if (pattern == null || pattern.Revision != ushort.MaxValue) { return pattern; } // MSDN doc on the attribute: // "The default build number increments daily. The default revision number is the number of seconds since midnight local time // (without taking into account time zone adjustments for daylight saving time), divided by 2." if (time == default(DateTime)) { time = DateTime.Now; } int revision = (int)time.TimeOfDay.TotalSeconds / 2; // 24 * 60 * 60 / 2 = 43200 < 65535 Debug.Assert(revision < ushort.MaxValue); if (pattern.Build == ushort.MaxValue) { TimeSpan days = time.Date - new DateTime(2000, 1, 1); int build = Math.Min(ushort.MaxValue, (int)days.TotalDays); return new Version(pattern.Major, pattern.Minor, (ushort)build, (ushort)revision); } else { return new Version(pattern.Major, pattern.Minor, pattern.Build, (ushort)revision); } } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/CSharp/Portable/Lowering/DiagnosticsPass_ExpressionTrees.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.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This pass detects and reports diagnostics that do not affect lambda convertibility. /// This part of the partial class focuses on features that cannot be used in expression trees. /// CAVEAT: Errors may be produced for ObsoleteAttribute, but such errors don't affect lambda convertibility. /// </summary> internal sealed partial class DiagnosticsPass { private readonly BindingDiagnosticBag _diagnostics; private readonly CSharpCompilation _compilation; private bool _inExpressionLambda; private bool _reportedUnsafe; private readonly MethodSymbol _containingSymbol; // Containing static local function, static anonymous function, or static lambda. private SourceMethodSymbol _staticLocalOrAnonymousFunction; public static void IssueDiagnostics(CSharpCompilation compilation, BoundNode node, BindingDiagnosticBag diagnostics, MethodSymbol containingSymbol) { Debug.Assert(node != null); Debug.Assert((object)containingSymbol != null); ExecutableCodeBinder.ValidateIteratorMethod(compilation, containingSymbol, diagnostics); try { var diagnosticPass = new DiagnosticsPass(compilation, diagnostics, containingSymbol); diagnosticPass.Visit(node); } catch (CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); } } private DiagnosticsPass(CSharpCompilation compilation, BindingDiagnosticBag diagnostics, MethodSymbol containingSymbol) { Debug.Assert(diagnostics != null); Debug.Assert((object)containingSymbol != null); _compilation = compilation; _diagnostics = diagnostics; _containingSymbol = containingSymbol; } private void Error(ErrorCode code, BoundNode node, params object[] args) { _diagnostics.Add(code, node.Syntax.Location, args); } private void CheckUnsafeType(BoundExpression e) { if (e != null && (object)e.Type != null && e.Type.IsPointerOrFunctionPointer()) NoteUnsafe(e); } private void NoteUnsafe(BoundNode node) { if (_inExpressionLambda && !_reportedUnsafe) { Error(ErrorCode.ERR_ExpressionTreeContainsPointerOp, node); _reportedUnsafe = true; } } public override BoundNode VisitArrayCreation(BoundArrayCreation node) { var arrayType = (ArrayTypeSymbol)node.Type; if (_inExpressionLambda && node.InitializerOpt != null && !arrayType.IsSZArray) { Error(ErrorCode.ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer, node); } return base.VisitArrayCreation(node); } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { if (_inExpressionLambda && node.Indices.Length == 1 && node.Indices[0].Type!.SpecialType == SpecialType.None) { Error(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, node); } return base.VisitArrayAccess(node); } public override BoundNode VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, node); } return base.VisitIndexOrRangePatternIndexerAccess(node); } public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsFromEndIndexExpression, node); } return base.VisitFromEndIndexExpression(node); } public override BoundNode VisitRangeExpression(BoundRangeExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsRangeExpression, node); } return base.VisitRangeExpression(node); } public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node) { if (_inExpressionLambda && node.ConstantValue == null) { Error(ErrorCode.ERR_ExpressionTreeContainsPointerOp, node); } return base.VisitSizeOfOperator(node); } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { ExecutableCodeBinder.ValidateIteratorMethod(_compilation, node.Symbol, _diagnostics); var outerLocalFunction = _staticLocalOrAnonymousFunction; if (node.Symbol.IsStatic) { _staticLocalOrAnonymousFunction = node.Symbol; } var result = base.VisitLocalFunctionStatement(node); _staticLocalOrAnonymousFunction = outerLocalFunction; return result; } public override BoundNode VisitThisReference(BoundThisReference node) { CheckReferenceToThisOrBase(node); return base.VisitThisReference(node); } public override BoundNode VisitBaseReference(BoundBaseReference node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsBaseAccess, node); } CheckReferenceToThisOrBase(node); return base.VisitBaseReference(node); } public override BoundNode VisitLocal(BoundLocal node) { CheckReferenceToVariable(node, node.LocalSymbol); return base.VisitLocal(node); } public override BoundNode VisitParameter(BoundParameter node) { CheckReferenceToVariable(node, node.ParameterSymbol); return base.VisitParameter(node); } private void CheckReferenceToThisOrBase(BoundExpression node) { if (_staticLocalOrAnonymousFunction is object) { var diagnostic = _staticLocalOrAnonymousFunction.MethodKind == MethodKind.LocalFunction ? ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis : ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis; Error(diagnostic, node); } } private void CheckReferenceToVariable(BoundExpression node, Symbol symbol) { Debug.Assert(symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Parameter || symbol is LocalFunctionSymbol); if (_staticLocalOrAnonymousFunction is object && Symbol.IsCaptured(symbol, _staticLocalOrAnonymousFunction)) { var diagnostic = _staticLocalOrAnonymousFunction.MethodKind == MethodKind.LocalFunction ? ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable : ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable; Error(diagnostic, node, new FormattedSymbol(symbol, SymbolDisplayFormat.ShortFormat)); } } private void CheckReferenceToMethodIfLocalFunction(BoundExpression node, MethodSymbol method) { if (method?.OriginalDefinition is LocalFunctionSymbol localFunction) { CheckReferenceToVariable(node, localFunction); } } public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsSwitchExpression, node); } return base.VisitConvertedSwitchExpression(node); } public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { if (!node.HasAnyErrors) { CheckForDeconstructionAssignmentToSelf((BoundTupleExpression)node.Left, node.Right); } return base.VisitDeconstructionAssignmentOperator(node); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { CheckForAssignmentToSelf(node); if (_inExpressionLambda && node.Left.Kind != BoundKind.ObjectInitializerMember && node.Left.Kind != BoundKind.DynamicObjectInitializerMember) { Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); } return base.VisitAssignmentOperator(node); } public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicObjectInitializerMember(node); } public override BoundNode VisitEventAccess(BoundEventAccess node) { // Don't bother reporting an obsolete diagnostic if the access is already wrong for other reasons // (specifically, we can't use it as a field here). if (node.IsUsableAsField) { bool hasBaseReceiver = node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.BaseReference; Binder.ReportDiagnosticsIfObsolete(_diagnostics, node.EventSymbol.AssociatedField, node.Syntax, hasBaseReceiver, _containingSymbol, _containingSymbol.ContainingType, BinderFlags.None); } CheckReceiverIfField(node.ReceiverOpt); return base.VisitEventAccess(node); } public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); } bool hasBaseReceiver = node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.BaseReference; Binder.ReportDiagnosticsIfObsolete(_diagnostics, node.Event, ((AssignmentExpressionSyntax)node.Syntax).Left, hasBaseReceiver, _containingSymbol, _containingSymbol.ContainingType, BinderFlags.None); CheckReceiverIfField(node.ReceiverOpt); return base.VisitEventAssignmentOperator(node); } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { CheckCompoundAssignmentOperator(node); return base.VisitCompoundAssignmentOperator(node); } private void VisitCall( MethodSymbol method, PropertySymbol propertyAccess, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<string> argumentNamesOpt, BitVector defaultArguments, BoundNode node) { Debug.Assert((object)method != null); Debug.Assert(((object)propertyAccess == null) || (method == propertyAccess.GetOwnOrInheritedGetMethod()) || (method == propertyAccess.GetOwnOrInheritedSetMethod()) || propertyAccess.MustCallMethodsDirectly); CheckArguments(argumentRefKindsOpt, arguments, method); if (_inExpressionLambda) { if (method.CallsAreOmitted(node.SyntaxTree)) { Error(ErrorCode.ERR_PartialMethodInExpressionTree, node); } else if ((object)propertyAccess != null && propertyAccess.IsIndexedProperty() && !propertyAccess.IsIndexer) { Error(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, node); } else if (hasDefaultArgument(arguments, defaultArguments)) { Error(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, node); } else if (!argumentNamesOpt.IsDefaultOrEmpty) { Error(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, node); } else if (IsComCallWithRefOmitted(method, arguments, argumentRefKindsOpt)) { Error(ErrorCode.ERR_ComRefCallInExpressionTree, node); } else if (method.MethodKind == MethodKind.LocalFunction) { Error(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, node); } else if (method.RefKind != RefKind.None) { Error(ErrorCode.ERR_RefReturningCallInExpressionTree, node); } else if (method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } } static bool hasDefaultArgument(ImmutableArray<BoundExpression> arguments, BitVector defaultArguments) { for (int i = 0; i < arguments.Length; i++) { if (defaultArguments[i]) { return true; } } return false; } } public override BoundNode Visit(BoundNode node) { if (_inExpressionLambda && // Ignoring BoundConversion nodes prevents redundant diagnostics !(node is BoundConversion) && node is BoundExpression expr && expr.Type is TypeSymbol type && type.IsRestrictedType()) { Error(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, node, type.Name); } return base.Visit(node); } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__reftype"); } return base.VisitRefTypeOperator(node); } public override BoundNode VisitRefValueOperator(BoundRefValueOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__refvalue"); } return base.VisitRefValueOperator(node); } public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__makeref"); } return base.VisitMakeRefOperator(node); } public override BoundNode VisitArgListOperator(BoundArgListOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_VarArgsInExpressionTree, node); } return base.VisitArgListOperator(node); } public override BoundNode VisitConditionalAccess(BoundConditionalAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_NullPropagatingOpInExpressionTree, node); } return base.VisitConditionalAccess(node); } public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) { if (_inExpressionLambda && !node.Arguments.IsDefaultOrEmpty) { Error(ErrorCode.ERR_DictionaryInitializerInExpressionTree, node); } if (node.MemberSymbol is PropertySymbol property) { CheckRefReturningPropertyAccess(node, property); } return base.VisitObjectInitializerMember(node); } public override BoundNode VisitCall(BoundCall node) { VisitCall(node.Method, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); CheckReceiverIfField(node.ReceiverOpt); CheckReferenceToMethodIfLocalFunction(node, node.Method); return base.VisitCall(node); } /// <summary> /// Called when a local represents an out variable declaration. Its syntax is of type DeclarationExpressionSyntax. /// </summary> private void CheckOutDeclaration(BoundLocal local) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsOutVariable, local); } } private void CheckDiscard(BoundDiscardExpression argument) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDiscard, argument); } } public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { if (_inExpressionLambda && node.AddMethod.IsStatic) { Error(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, node); } VisitCall(node.AddMethod, null, node.Arguments, default(ImmutableArray<RefKind>), default(ImmutableArray<string>), node.DefaultArguments, node); return base.VisitCollectionElementInitializer(node); } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { VisitCall(node.Constructor, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); return base.VisitObjectCreationExpression(node); } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { var indexer = node.Indexer; var method = indexer.GetOwnOrInheritedGetMethod() ?? indexer.GetOwnOrInheritedSetMethod(); if ((object)method != null) { VisitCall(method, indexer, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); } CheckReceiverIfField(node.ReceiverOpt); return base.VisitIndexerAccess(node); } private void CheckRefReturningPropertyAccess(BoundNode node, PropertySymbol property) { if (_inExpressionLambda && property.RefKind != RefKind.None) { Error(ErrorCode.ERR_RefReturningCallInExpressionTree, node); } } public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; CheckRefReturningPropertyAccess(node, property); CheckReceiverIfField(node.ReceiverOpt); if (_inExpressionLambda && property.IsAbstract && property.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } return base.VisitPropertyAccess(node); } public override BoundNode VisitLambda(BoundLambda node) { if (_inExpressionLambda) { var lambda = node.Symbol; foreach (var p in lambda.Parameters) { if (p.RefKind != RefKind.None && p.Locations.Length != 0) { _diagnostics.Add(ErrorCode.ERR_ByRefParameterInExpressionTree, p.Locations[0]); } if (p.TypeWithAnnotations.IsRestrictedType()) { _diagnostics.Add(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, p.Locations[0], p.Type.Name); } } switch (node.Syntax.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: { var lambdaSyntax = (ParenthesizedLambdaExpressionSyntax)node.Syntax; if (lambdaSyntax.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword) { Error(ErrorCode.ERR_BadAsyncExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.Block) { Error(ErrorCode.ERR_StatementLambdaToExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.RefExpression) { Error(ErrorCode.ERR_BadRefReturnExpressionTree, node); } } break; case SyntaxKind.SimpleLambdaExpression: { var lambdaSyntax = (SimpleLambdaExpressionSyntax)node.Syntax; if (lambdaSyntax.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword) { Error(ErrorCode.ERR_BadAsyncExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.Block) { Error(ErrorCode.ERR_StatementLambdaToExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.RefExpression) { Error(ErrorCode.ERR_BadRefReturnExpressionTree, node); } } break; case SyntaxKind.AnonymousMethodExpression: Error(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, node); break; default: // other syntax forms arise from query expressions, and always result from implied expression-lambda-like forms break; } } var outerLocalFunction = _staticLocalOrAnonymousFunction; if (node.Symbol.IsStatic) { _staticLocalOrAnonymousFunction = node.Symbol; } var result = base.VisitLambda(node); _staticLocalOrAnonymousFunction = outerLocalFunction; return result; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { // It is very common for bound trees to be left-heavy binary operators, eg, // a + b + c + d + ... // To avoid blowing the stack, do not recurse down the left hand side. // In order to avoid blowing the stack, we end up visiting right children // before left children; this should not be a problem in the diagnostics // pass. BoundBinaryOperator current = node; while (true) { CheckBinaryOperator(current); Visit(current.Right); if (current.Left.Kind == BoundKind.BinaryOperator) { current = (BoundBinaryOperator)current.Left; } else { Visit(current.Left); break; } } return null; } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { CheckLiftedUserDefinedConditionalLogicalOperator(node); if (_inExpressionLambda) { var binary = node.LogicalOperator; var unary = node.OperatorKind.Operator() == BinaryOperatorKind.And ? node.FalseOperator : node.TrueOperator; if ((binary.IsAbstract && binary.IsStatic) || (unary.IsAbstract && unary.IsStatic)) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } } return base.VisitUserDefinedConditionalLogicalOperator(node); } private void CheckDynamic(BoundUnaryOperator node) { if (_inExpressionLambda && node.OperatorKind.IsDynamic()) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } } private void CheckDynamic(BoundBinaryOperator node) { if (_inExpressionLambda && node.OperatorKind.IsDynamic()) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } } public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) { CheckUnsafeType(node); CheckLiftedUnaryOp(node); CheckDynamic(node); if (_inExpressionLambda && node.MethodOpt is MethodSymbol method && method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } return base.VisitUnaryOperator(node); } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { CheckUnsafeType(node); BoundExpression operand = node.Operand; if (operand.Kind == BoundKind.FieldAccess) { CheckFieldAddress((BoundFieldAccess)operand, consumerOpt: null); } return base.VisitAddressOfOperator(node); } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); } return base.VisitIncrementOperator(node); } public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { NoteUnsafe(node); return base.VisitPointerElementAccess(node); } public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { NoteUnsafe(node); return base.VisitPointerIndirectionOperator(node); } public override BoundNode VisitConversion(BoundConversion node) { CheckUnsafeType(node.Operand); CheckUnsafeType(node); bool wasInExpressionLambda = _inExpressionLambda; bool oldReportedUnsafe = _reportedUnsafe; switch (node.ConversionKind) { case ConversionKind.MethodGroup: CheckMethodGroup((BoundMethodGroup)node.Operand, node.Conversion.Method, parentIsConversion: true, node.Type); return node; case ConversionKind.AnonymousFunction: if (!wasInExpressionLambda && node.Type.IsExpressionTree()) { _inExpressionLambda = true; // we report "unsafe in expression tree" at most once for each expression tree _reportedUnsafe = false; } break; case ConversionKind.ImplicitDynamic: case ConversionKind.ExplicitDynamic: if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } break; case ConversionKind.ExplicitTuple: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleConversion, node); } break; case ConversionKind.InterpolatedStringHandler: if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, node); } break; default: if (_inExpressionLambda && node.Conversion.Method is MethodSymbol method && method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } break; } var result = base.VisitConversion(node); _inExpressionLambda = wasInExpressionLambda; _reportedUnsafe = oldReportedUnsafe; return result; } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { if (node.Argument.Kind != BoundKind.MethodGroup) { this.Visit(node.Argument); } else { CheckMethodGroup((BoundMethodGroup)node.Argument, node.MethodOpt, parentIsConversion: true, convertedToType: node.Type); } return null; } public override BoundNode VisitMethodGroup(BoundMethodGroup node) { CheckMethodGroup(node, method: null, parentIsConversion: false, convertedToType: null); return null; } private void CheckMethodGroup(BoundMethodGroup node, MethodSymbol method, bool parentIsConversion, TypeSymbol convertedToType) { // Formerly reported ERR_MemGroupInExpressionTree when this occurred, but the expanded // ERR_LambdaInIsAs makes this impossible (since the node will always be wrapped in // a failed conversion). Debug.Assert(!(!parentIsConversion && _inExpressionLambda)); if (_inExpressionLambda) { if ((node.LookupSymbolOpt as MethodSymbol)?.MethodKind == MethodKind.LocalFunction) { Error(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, node); } else if (parentIsConversion && convertedToType.IsFunctionPointer()) { Error(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, node); } else if (method is not null && method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } } CheckReceiverIfField(node.ReceiverOpt); CheckReferenceToMethodIfLocalFunction(node, method); if (method is null || method.RequiresInstanceReceiver) { Visit(node.ReceiverOpt); } } public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) { // The nameof(...) operator collapses to a constant in an expression tree, // so it does not matter what is recursively within it. return node; } public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { if (_inExpressionLambda && (node.LeftOperand.IsLiteralNull() || node.LeftOperand.IsLiteralDefault())) { Error(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, node.LeftOperand); } return base.VisitNullCoalescingOperator(node); } public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeCantContainNullCoalescingAssignment, node); } return base.VisitNullCoalescingAssignmentOperator(node); } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); // avoid reporting errors for the method group: if (node.Expression.Kind == BoundKind.MethodGroup) { return base.VisitMethodGroup((BoundMethodGroup)node.Expression); } } return base.VisitDynamicInvocation(node); } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } CheckReceiverIfField(node.Receiver); return base.VisitDynamicIndexerAccess(node); } public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicMemberAccess(node); } public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicCollectionElementInitializer(node); } public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicObjectCreationExpression(node); } public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsIsMatch, node); } return base.VisitIsPatternExpression(node); } public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, node); } return base.VisitConvertedTupleLiteral(node); } public override BoundNode VisitTupleLiteral(BoundTupleLiteral node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, node); } return base.VisitTupleLiteral(node); } public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, node); } return base.VisitTupleBinaryOperator(node); } public override BoundNode VisitThrowExpression(BoundThrowExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, node); } return base.VisitThrowExpression(node); } public override BoundNode VisitWithExpression(BoundWithExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsWithExpression, node); } return base.VisitWithExpression(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. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This pass detects and reports diagnostics that do not affect lambda convertibility. /// This part of the partial class focuses on features that cannot be used in expression trees. /// CAVEAT: Errors may be produced for ObsoleteAttribute, but such errors don't affect lambda convertibility. /// </summary> internal sealed partial class DiagnosticsPass { private readonly BindingDiagnosticBag _diagnostics; private readonly CSharpCompilation _compilation; private bool _inExpressionLambda; private bool _reportedUnsafe; private readonly MethodSymbol _containingSymbol; // Containing static local function, static anonymous function, or static lambda. private SourceMethodSymbol _staticLocalOrAnonymousFunction; public static void IssueDiagnostics(CSharpCompilation compilation, BoundNode node, BindingDiagnosticBag diagnostics, MethodSymbol containingSymbol) { Debug.Assert(node != null); Debug.Assert((object)containingSymbol != null); ExecutableCodeBinder.ValidateIteratorMethod(compilation, containingSymbol, diagnostics); try { var diagnosticPass = new DiagnosticsPass(compilation, diagnostics, containingSymbol); diagnosticPass.Visit(node); } catch (CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); } } private DiagnosticsPass(CSharpCompilation compilation, BindingDiagnosticBag diagnostics, MethodSymbol containingSymbol) { Debug.Assert(diagnostics != null); Debug.Assert((object)containingSymbol != null); _compilation = compilation; _diagnostics = diagnostics; _containingSymbol = containingSymbol; } private void Error(ErrorCode code, BoundNode node, params object[] args) { _diagnostics.Add(code, node.Syntax.Location, args); } private void CheckUnsafeType(BoundExpression e) { if (e != null && (object)e.Type != null && e.Type.IsPointerOrFunctionPointer()) NoteUnsafe(e); } private void NoteUnsafe(BoundNode node) { if (_inExpressionLambda && !_reportedUnsafe) { Error(ErrorCode.ERR_ExpressionTreeContainsPointerOp, node); _reportedUnsafe = true; } } public override BoundNode VisitArrayCreation(BoundArrayCreation node) { var arrayType = (ArrayTypeSymbol)node.Type; if (_inExpressionLambda && node.InitializerOpt != null && !arrayType.IsSZArray) { Error(ErrorCode.ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer, node); } return base.VisitArrayCreation(node); } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { if (_inExpressionLambda && node.Indices.Length == 1 && node.Indices[0].Type!.SpecialType == SpecialType.None) { Error(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, node); } return base.VisitArrayAccess(node); } public override BoundNode VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, node); } return base.VisitIndexOrRangePatternIndexerAccess(node); } public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsFromEndIndexExpression, node); } return base.VisitFromEndIndexExpression(node); } public override BoundNode VisitRangeExpression(BoundRangeExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsRangeExpression, node); } return base.VisitRangeExpression(node); } public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node) { if (_inExpressionLambda && node.ConstantValue == null) { Error(ErrorCode.ERR_ExpressionTreeContainsPointerOp, node); } return base.VisitSizeOfOperator(node); } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { ExecutableCodeBinder.ValidateIteratorMethod(_compilation, node.Symbol, _diagnostics); var outerLocalFunction = _staticLocalOrAnonymousFunction; if (node.Symbol.IsStatic) { _staticLocalOrAnonymousFunction = node.Symbol; } var result = base.VisitLocalFunctionStatement(node); _staticLocalOrAnonymousFunction = outerLocalFunction; return result; } public override BoundNode VisitThisReference(BoundThisReference node) { CheckReferenceToThisOrBase(node); return base.VisitThisReference(node); } public override BoundNode VisitBaseReference(BoundBaseReference node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsBaseAccess, node); } CheckReferenceToThisOrBase(node); return base.VisitBaseReference(node); } public override BoundNode VisitLocal(BoundLocal node) { CheckReferenceToVariable(node, node.LocalSymbol); return base.VisitLocal(node); } public override BoundNode VisitParameter(BoundParameter node) { CheckReferenceToVariable(node, node.ParameterSymbol); return base.VisitParameter(node); } private void CheckReferenceToThisOrBase(BoundExpression node) { if (_staticLocalOrAnonymousFunction is object) { var diagnostic = _staticLocalOrAnonymousFunction.MethodKind == MethodKind.LocalFunction ? ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis : ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis; Error(diagnostic, node); } } private void CheckReferenceToVariable(BoundExpression node, Symbol symbol) { Debug.Assert(symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Parameter || symbol is LocalFunctionSymbol); if (_staticLocalOrAnonymousFunction is object && Symbol.IsCaptured(symbol, _staticLocalOrAnonymousFunction)) { var diagnostic = _staticLocalOrAnonymousFunction.MethodKind == MethodKind.LocalFunction ? ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable : ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable; Error(diagnostic, node, new FormattedSymbol(symbol, SymbolDisplayFormat.ShortFormat)); } } private void CheckReferenceToMethodIfLocalFunction(BoundExpression node, MethodSymbol method) { if (method?.OriginalDefinition is LocalFunctionSymbol localFunction) { CheckReferenceToVariable(node, localFunction); } } public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsSwitchExpression, node); } return base.VisitConvertedSwitchExpression(node); } public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { if (!node.HasAnyErrors) { CheckForDeconstructionAssignmentToSelf((BoundTupleExpression)node.Left, node.Right); } return base.VisitDeconstructionAssignmentOperator(node); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { CheckForAssignmentToSelf(node); if (_inExpressionLambda && node.Left.Kind != BoundKind.ObjectInitializerMember && node.Left.Kind != BoundKind.DynamicObjectInitializerMember) { Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); } return base.VisitAssignmentOperator(node); } public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicObjectInitializerMember(node); } public override BoundNode VisitEventAccess(BoundEventAccess node) { // Don't bother reporting an obsolete diagnostic if the access is already wrong for other reasons // (specifically, we can't use it as a field here). if (node.IsUsableAsField) { bool hasBaseReceiver = node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.BaseReference; Binder.ReportDiagnosticsIfObsolete(_diagnostics, node.EventSymbol.AssociatedField, node.Syntax, hasBaseReceiver, _containingSymbol, _containingSymbol.ContainingType, BinderFlags.None); } CheckReceiverIfField(node.ReceiverOpt); return base.VisitEventAccess(node); } public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); } bool hasBaseReceiver = node.ReceiverOpt != null && node.ReceiverOpt.Kind == BoundKind.BaseReference; Binder.ReportDiagnosticsIfObsolete(_diagnostics, node.Event, ((AssignmentExpressionSyntax)node.Syntax).Left, hasBaseReceiver, _containingSymbol, _containingSymbol.ContainingType, BinderFlags.None); CheckReceiverIfField(node.ReceiverOpt); return base.VisitEventAssignmentOperator(node); } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { CheckCompoundAssignmentOperator(node); return base.VisitCompoundAssignmentOperator(node); } private void VisitCall( MethodSymbol method, PropertySymbol propertyAccess, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<string> argumentNamesOpt, BitVector defaultArguments, BoundNode node) { Debug.Assert((object)method != null); Debug.Assert(((object)propertyAccess == null) || (method == propertyAccess.GetOwnOrInheritedGetMethod()) || (method == propertyAccess.GetOwnOrInheritedSetMethod()) || propertyAccess.MustCallMethodsDirectly); CheckArguments(argumentRefKindsOpt, arguments, method); if (_inExpressionLambda) { if (method.CallsAreOmitted(node.SyntaxTree)) { Error(ErrorCode.ERR_PartialMethodInExpressionTree, node); } else if ((object)propertyAccess != null && propertyAccess.IsIndexedProperty() && !propertyAccess.IsIndexer) { Error(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, node); } else if (hasDefaultArgument(arguments, defaultArguments)) { Error(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, node); } else if (!argumentNamesOpt.IsDefaultOrEmpty) { Error(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, node); } else if (IsComCallWithRefOmitted(method, arguments, argumentRefKindsOpt)) { Error(ErrorCode.ERR_ComRefCallInExpressionTree, node); } else if (method.MethodKind == MethodKind.LocalFunction) { Error(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, node); } else if (method.RefKind != RefKind.None) { Error(ErrorCode.ERR_RefReturningCallInExpressionTree, node); } else if (method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } } static bool hasDefaultArgument(ImmutableArray<BoundExpression> arguments, BitVector defaultArguments) { for (int i = 0; i < arguments.Length; i++) { if (defaultArguments[i]) { return true; } } return false; } } public override BoundNode Visit(BoundNode node) { if (_inExpressionLambda && // Ignoring BoundConversion nodes prevents redundant diagnostics !(node is BoundConversion) && node is BoundExpression expr && expr.Type is TypeSymbol type && type.IsRestrictedType()) { Error(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, node, type.Name); } return base.Visit(node); } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__reftype"); } return base.VisitRefTypeOperator(node); } public override BoundNode VisitRefValueOperator(BoundRefValueOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__refvalue"); } return base.VisitRefValueOperator(node); } public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_FeatureNotValidInExpressionTree, node, "__makeref"); } return base.VisitMakeRefOperator(node); } public override BoundNode VisitArgListOperator(BoundArgListOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_VarArgsInExpressionTree, node); } return base.VisitArgListOperator(node); } public override BoundNode VisitConditionalAccess(BoundConditionalAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_NullPropagatingOpInExpressionTree, node); } return base.VisitConditionalAccess(node); } public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) { if (_inExpressionLambda && !node.Arguments.IsDefaultOrEmpty) { Error(ErrorCode.ERR_DictionaryInitializerInExpressionTree, node); } if (node.MemberSymbol is PropertySymbol property) { CheckRefReturningPropertyAccess(node, property); } return base.VisitObjectInitializerMember(node); } public override BoundNode VisitCall(BoundCall node) { VisitCall(node.Method, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); CheckReceiverIfField(node.ReceiverOpt); CheckReferenceToMethodIfLocalFunction(node, node.Method); return base.VisitCall(node); } /// <summary> /// Called when a local represents an out variable declaration. Its syntax is of type DeclarationExpressionSyntax. /// </summary> private void CheckOutDeclaration(BoundLocal local) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsOutVariable, local); } } private void CheckDiscard(BoundDiscardExpression argument) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDiscard, argument); } } public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { if (_inExpressionLambda && node.AddMethod.IsStatic) { Error(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, node); } VisitCall(node.AddMethod, null, node.Arguments, default(ImmutableArray<RefKind>), default(ImmutableArray<string>), node.DefaultArguments, node); return base.VisitCollectionElementInitializer(node); } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { VisitCall(node.Constructor, null, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); return base.VisitObjectCreationExpression(node); } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { var indexer = node.Indexer; var method = indexer.GetOwnOrInheritedGetMethod() ?? indexer.GetOwnOrInheritedSetMethod(); if ((object)method != null) { VisitCall(method, indexer, node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt, node.DefaultArguments, node); } CheckReceiverIfField(node.ReceiverOpt); return base.VisitIndexerAccess(node); } private void CheckRefReturningPropertyAccess(BoundNode node, PropertySymbol property) { if (_inExpressionLambda && property.RefKind != RefKind.None) { Error(ErrorCode.ERR_RefReturningCallInExpressionTree, node); } } public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; CheckRefReturningPropertyAccess(node, property); CheckReceiverIfField(node.ReceiverOpt); if (_inExpressionLambda && property.IsAbstract && property.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } return base.VisitPropertyAccess(node); } public override BoundNode VisitLambda(BoundLambda node) { if (_inExpressionLambda) { var lambda = node.Symbol; foreach (var p in lambda.Parameters) { if (p.RefKind != RefKind.None && p.Locations.Length != 0) { _diagnostics.Add(ErrorCode.ERR_ByRefParameterInExpressionTree, p.Locations[0]); } if (p.TypeWithAnnotations.IsRestrictedType()) { _diagnostics.Add(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, p.Locations[0], p.Type.Name); } } switch (node.Syntax.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: { var lambdaSyntax = (ParenthesizedLambdaExpressionSyntax)node.Syntax; if (lambdaSyntax.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword) { Error(ErrorCode.ERR_BadAsyncExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.Block) { Error(ErrorCode.ERR_StatementLambdaToExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.RefExpression) { Error(ErrorCode.ERR_BadRefReturnExpressionTree, node); } } break; case SyntaxKind.SimpleLambdaExpression: { var lambdaSyntax = (SimpleLambdaExpressionSyntax)node.Syntax; if (lambdaSyntax.AsyncKeyword.Kind() == SyntaxKind.AsyncKeyword) { Error(ErrorCode.ERR_BadAsyncExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.Block) { Error(ErrorCode.ERR_StatementLambdaToExpressionTree, node); } else if (lambdaSyntax.Body.Kind() == SyntaxKind.RefExpression) { Error(ErrorCode.ERR_BadRefReturnExpressionTree, node); } } break; case SyntaxKind.AnonymousMethodExpression: Error(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, node); break; default: // other syntax forms arise from query expressions, and always result from implied expression-lambda-like forms break; } } var outerLocalFunction = _staticLocalOrAnonymousFunction; if (node.Symbol.IsStatic) { _staticLocalOrAnonymousFunction = node.Symbol; } var result = base.VisitLambda(node); _staticLocalOrAnonymousFunction = outerLocalFunction; return result; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { // It is very common for bound trees to be left-heavy binary operators, eg, // a + b + c + d + ... // To avoid blowing the stack, do not recurse down the left hand side. // In order to avoid blowing the stack, we end up visiting right children // before left children; this should not be a problem in the diagnostics // pass. BoundBinaryOperator current = node; while (true) { CheckBinaryOperator(current); Visit(current.Right); if (current.Left.Kind == BoundKind.BinaryOperator) { current = (BoundBinaryOperator)current.Left; } else { Visit(current.Left); break; } } return null; } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { CheckLiftedUserDefinedConditionalLogicalOperator(node); if (_inExpressionLambda) { var binary = node.LogicalOperator; var unary = node.OperatorKind.Operator() == BinaryOperatorKind.And ? node.FalseOperator : node.TrueOperator; if ((binary.IsAbstract && binary.IsStatic) || (unary.IsAbstract && unary.IsStatic)) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } } return base.VisitUserDefinedConditionalLogicalOperator(node); } private void CheckDynamic(BoundUnaryOperator node) { if (_inExpressionLambda && node.OperatorKind.IsDynamic()) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } } private void CheckDynamic(BoundBinaryOperator node) { if (_inExpressionLambda && node.OperatorKind.IsDynamic()) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } } public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) { CheckUnsafeType(node); CheckLiftedUnaryOp(node); CheckDynamic(node); if (_inExpressionLambda && node.MethodOpt is MethodSymbol method && method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } return base.VisitUnaryOperator(node); } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { CheckUnsafeType(node); BoundExpression operand = node.Operand; if (operand.Kind == BoundKind.FieldAccess) { CheckFieldAddress((BoundFieldAccess)operand, consumerOpt: null); } return base.VisitAddressOfOperator(node); } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node); } return base.VisitIncrementOperator(node); } public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { NoteUnsafe(node); return base.VisitPointerElementAccess(node); } public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { NoteUnsafe(node); return base.VisitPointerIndirectionOperator(node); } public override BoundNode VisitConversion(BoundConversion node) { CheckUnsafeType(node.Operand); CheckUnsafeType(node); bool wasInExpressionLambda = _inExpressionLambda; bool oldReportedUnsafe = _reportedUnsafe; switch (node.ConversionKind) { case ConversionKind.MethodGroup: CheckMethodGroup((BoundMethodGroup)node.Operand, node.Conversion.Method, parentIsConversion: true, node.Type); return node; case ConversionKind.AnonymousFunction: if (!wasInExpressionLambda && node.Type.IsExpressionTree()) { _inExpressionLambda = true; // we report "unsafe in expression tree" at most once for each expression tree _reportedUnsafe = false; } break; case ConversionKind.ImplicitDynamic: case ConversionKind.ExplicitDynamic: if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } break; case ConversionKind.ExplicitTuple: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleConversion, node); } break; case ConversionKind.InterpolatedStringHandler: if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, node); } break; default: if (_inExpressionLambda && node.Conversion.Method is MethodSymbol method && method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } break; } var result = base.VisitConversion(node); _inExpressionLambda = wasInExpressionLambda; _reportedUnsafe = oldReportedUnsafe; return result; } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { if (node.Argument.Kind != BoundKind.MethodGroup) { this.Visit(node.Argument); } else { CheckMethodGroup((BoundMethodGroup)node.Argument, node.MethodOpt, parentIsConversion: true, convertedToType: node.Type); } return null; } public override BoundNode VisitMethodGroup(BoundMethodGroup node) { CheckMethodGroup(node, method: null, parentIsConversion: false, convertedToType: null); return null; } private void CheckMethodGroup(BoundMethodGroup node, MethodSymbol method, bool parentIsConversion, TypeSymbol convertedToType) { // Formerly reported ERR_MemGroupInExpressionTree when this occurred, but the expanded // ERR_LambdaInIsAs makes this impossible (since the node will always be wrapped in // a failed conversion). Debug.Assert(!(!parentIsConversion && _inExpressionLambda)); if (_inExpressionLambda) { if ((node.LookupSymbolOpt as MethodSymbol)?.MethodKind == MethodKind.LocalFunction) { Error(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, node); } else if (parentIsConversion && convertedToType.IsFunctionPointer()) { Error(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, node); } else if (method is not null && method.IsAbstract && method.IsStatic) { Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node); } } CheckReceiverIfField(node.ReceiverOpt); CheckReferenceToMethodIfLocalFunction(node, method); if (method is null || method.RequiresInstanceReceiver) { Visit(node.ReceiverOpt); } } public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) { // The nameof(...) operator collapses to a constant in an expression tree, // so it does not matter what is recursively within it. return node; } public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { if (_inExpressionLambda && (node.LeftOperand.IsLiteralNull() || node.LeftOperand.IsLiteralDefault())) { Error(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, node.LeftOperand); } return base.VisitNullCoalescingOperator(node); } public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeCantContainNullCoalescingAssignment, node); } return base.VisitNullCoalescingAssignmentOperator(node); } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); // avoid reporting errors for the method group: if (node.Expression.Kind == BoundKind.MethodGroup) { return base.VisitMethodGroup((BoundMethodGroup)node.Expression); } } return base.VisitDynamicInvocation(node); } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } CheckReceiverIfField(node.Receiver); return base.VisitDynamicIndexerAccess(node); } public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicMemberAccess(node); } public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicCollectionElementInitializer(node); } public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsDynamicOperation, node); } return base.VisitDynamicObjectCreationExpression(node); } public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsIsMatch, node); } return base.VisitIsPatternExpression(node); } public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, node); } return base.VisitConvertedTupleLiteral(node); } public override BoundNode VisitTupleLiteral(BoundTupleLiteral node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, node); } return base.VisitTupleLiteral(node); } public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, node); } return base.VisitTupleBinaryOperator(node); } public override BoundNode VisitThrowExpression(BoundThrowExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, node); } return base.VisitThrowExpression(node); } public override BoundNode VisitWithExpression(BoundWithExpression node) { if (_inExpressionLambda) { Error(ErrorCode.ERR_ExpressionTreeContainsWithExpression, node); } return base.VisitWithExpression(node); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/AbstractKeywordRecommender.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.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders Friend MustInherit Class AbstractKeywordRecommender Implements IKeywordRecommender(Of VisualBasicSyntaxContext) Public Function RecommendKeywords( position As Integer, context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Implements IKeywordRecommender(Of VisualBasicSyntaxContext).RecommendKeywords Return RecommendKeywords(context, cancellationToken) End Function Friend Function RecommendKeywords_Test(context As VisualBasicSyntaxContext) As ImmutableArray(Of RecommendedKeyword) Return RecommendKeywords(context, CancellationToken.None) End Function Protected MustOverride Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) 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.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders Friend MustInherit Class AbstractKeywordRecommender Implements IKeywordRecommender(Of VisualBasicSyntaxContext) Public Function RecommendKeywords( position As Integer, context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Implements IKeywordRecommender(Of VisualBasicSyntaxContext).RecommendKeywords Return RecommendKeywords(context, cancellationToken) End Function Friend Function RecommendKeywords_Test(context As VisualBasicSyntaxContext) As ImmutableArray(Of RecommendedKeyword) Return RecommendKeywords(context, CancellationToken.None) End Function Protected MustOverride Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.UnavailableTypeParameterRemover.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.Linq; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ITypeSymbolExtensions { private class UnavailableTypeParameterRemover : SymbolVisitor<ITypeSymbol> { private readonly Compilation _compilation; private readonly ISet<string> _availableTypeParameterNames; public UnavailableTypeParameterRemover(Compilation compilation, ISet<string> availableTypeParameterNames) { _compilation = compilation; _availableTypeParameterNames = availableTypeParameterNames; } public override ITypeSymbol DefaultVisit(ISymbol node) => throw new NotImplementedException(); public override ITypeSymbol VisitDynamicType(IDynamicTypeSymbol symbol) => symbol; public override ITypeSymbol VisitArrayType(IArrayTypeSymbol symbol) { var elementType = symbol.ElementType.Accept(this); if (elementType != null && elementType.Equals(symbol.ElementType)) { return symbol; } return _compilation.CreateArrayTypeSymbol(elementType, symbol.Rank); } public override ITypeSymbol VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { // TODO(https://github.com/dotnet/roslyn/issues/43890): implement this return symbol; } public override ITypeSymbol VisitNamedType(INamedTypeSymbol symbol) { var arguments = symbol.TypeArguments.Select(t => t.Accept(this)).ToArray(); if (arguments.SequenceEqual(symbol.TypeArguments)) { return symbol; } return symbol.ConstructedFrom.Construct(arguments.ToArray()); } public override ITypeSymbol VisitPointerType(IPointerTypeSymbol symbol) { var elementType = symbol.PointedAtType.Accept(this); if (elementType != null && elementType.Equals(symbol.PointedAtType)) { return symbol; } return _compilation.CreatePointerTypeSymbol(elementType); } public override ITypeSymbol VisitTypeParameter(ITypeParameterSymbol symbol) { if (_availableTypeParameterNames.Contains(symbol.Name)) { return symbol; } return _compilation.ObjectType; } } } }
// 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.Linq; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ITypeSymbolExtensions { private class UnavailableTypeParameterRemover : SymbolVisitor<ITypeSymbol> { private readonly Compilation _compilation; private readonly ISet<string> _availableTypeParameterNames; public UnavailableTypeParameterRemover(Compilation compilation, ISet<string> availableTypeParameterNames) { _compilation = compilation; _availableTypeParameterNames = availableTypeParameterNames; } public override ITypeSymbol DefaultVisit(ISymbol node) => throw new NotImplementedException(); public override ITypeSymbol VisitDynamicType(IDynamicTypeSymbol symbol) => symbol; public override ITypeSymbol VisitArrayType(IArrayTypeSymbol symbol) { var elementType = symbol.ElementType.Accept(this); if (elementType != null && elementType.Equals(symbol.ElementType)) { return symbol; } return _compilation.CreateArrayTypeSymbol(elementType, symbol.Rank); } public override ITypeSymbol VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { // TODO(https://github.com/dotnet/roslyn/issues/43890): implement this return symbol; } public override ITypeSymbol VisitNamedType(INamedTypeSymbol symbol) { var arguments = symbol.TypeArguments.Select(t => t.Accept(this)).ToArray(); if (arguments.SequenceEqual(symbol.TypeArguments)) { return symbol; } return symbol.ConstructedFrom.Construct(arguments.ToArray()); } public override ITypeSymbol VisitPointerType(IPointerTypeSymbol symbol) { var elementType = symbol.PointedAtType.Accept(this); if (elementType != null && elementType.Equals(symbol.PointedAtType)) { return symbol; } return _compilation.CreatePointerTypeSymbol(elementType); } public override ITypeSymbol VisitTypeParameter(ITypeParameterSymbol symbol) { if (_availableTypeParameterNames.Contains(symbol.Name)) { return symbol; } return _compilation.ObjectType; } } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayPartKind.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 { /// <summary> /// Specifies the kinds of a piece of classified text (SymbolDisplayPart). /// </summary> public enum SymbolDisplayPartKind { /// <summary>The name of an alias.</summary> AliasName = 0, /// <summary>The name of an assembly.</summary> AssemblyName = 1, /// <summary>The name of a class.</summary> ClassName = 2, /// <summary>The name of a delegate.</summary> DelegateName = 3, /// <summary>The name of an enum.</summary> EnumName = 4, /// <summary>The name of an error type.</summary> /// <seealso cref="IErrorTypeSymbol"/> ErrorTypeName = 5, /// <summary>The name of an event.</summary> EventName = 6, /// <summary>The name of a field.</summary> FieldName = 7, /// <summary>The name of an interface.</summary> InterfaceName = 8, /// <summary>A language keyword.</summary> Keyword = 9, /// <summary>The name of a label.</summary> LabelName = 10, /// <summary>A line-break (i.e. whitespace).</summary> LineBreak = 11, /// <summary>A numeric literal.</summary> /// <remarks>Typically for the default values of parameters and the constant values of fields.</remarks> NumericLiteral = 12, /// <summary>A string literal.</summary> /// <remarks>Typically for the default values of parameters and the constant values of fields.</remarks> StringLiteral = 13, /// <summary>The name of a local.</summary> LocalName = 14, /// <summary>The name of a method.</summary> MethodName = 15, /// <summary>The name of a module.</summary> ModuleName = 16, /// <summary>The name of a namespace.</summary> NamespaceName = 17, /// <summary>The symbol of an operator (e.g. "+").</summary> Operator = 18, /// <summary>The name of a parameter.</summary> ParameterName = 19, /// <summary>The name of a property.</summary> PropertyName = 20, /// <summary>A punctuation character (e.g. "(", ".", ",") other than an <see cref="Operator"/>.</summary> Punctuation = 21, /// <summary>A single space character.</summary> Space = 22, /// <summary>The name of a struct (structure in Visual Basic).</summary> StructName = 23, /// <summary>A keyword-like part for anonymous types (not actually a keyword).</summary> AnonymousTypeIndicator = 24, /// <summary>An unclassified part.</summary> /// <remarks>Never returned - only set in user-constructed parts.</remarks> Text = 25, /// <summary>The name of a type parameter.</summary> TypeParameterName = 26, /// <summary>The name of a query range variable.</summary> RangeVariableName = 27, /// <summary>The name of an enum member.</summary> EnumMemberName = 28, /// <summary>The name of a reduced extension method.</summary> /// <remarks> /// When an extension method is in it's non-reduced form it will be will be marked as MethodName. /// </remarks> ExtensionMethodName = 29, /// <summary>The name of a field or local constant.</summary> ConstantName = 30, /// <summary>The name of a record class.</summary> RecordClassName = 31, /// <summary>The name of a record struct.</summary> RecordStructName = 32, } internal static class InternalSymbolDisplayPartKind { private const SymbolDisplayPartKind @base = SymbolDisplayPartKind.RecordStructName + 1; public const SymbolDisplayPartKind Arity = @base + 0; public const SymbolDisplayPartKind Other = @base + 1; } internal static partial class EnumBounds { internal static bool IsValid(this SymbolDisplayPartKind value) { return (value >= SymbolDisplayPartKind.AliasName && value <= SymbolDisplayPartKind.RecordStructName) || (value >= InternalSymbolDisplayPartKind.Arity && value <= InternalSymbolDisplayPartKind.Other); } } }
// 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 { /// <summary> /// Specifies the kinds of a piece of classified text (SymbolDisplayPart). /// </summary> public enum SymbolDisplayPartKind { /// <summary>The name of an alias.</summary> AliasName = 0, /// <summary>The name of an assembly.</summary> AssemblyName = 1, /// <summary>The name of a class.</summary> ClassName = 2, /// <summary>The name of a delegate.</summary> DelegateName = 3, /// <summary>The name of an enum.</summary> EnumName = 4, /// <summary>The name of an error type.</summary> /// <seealso cref="IErrorTypeSymbol"/> ErrorTypeName = 5, /// <summary>The name of an event.</summary> EventName = 6, /// <summary>The name of a field.</summary> FieldName = 7, /// <summary>The name of an interface.</summary> InterfaceName = 8, /// <summary>A language keyword.</summary> Keyword = 9, /// <summary>The name of a label.</summary> LabelName = 10, /// <summary>A line-break (i.e. whitespace).</summary> LineBreak = 11, /// <summary>A numeric literal.</summary> /// <remarks>Typically for the default values of parameters and the constant values of fields.</remarks> NumericLiteral = 12, /// <summary>A string literal.</summary> /// <remarks>Typically for the default values of parameters and the constant values of fields.</remarks> StringLiteral = 13, /// <summary>The name of a local.</summary> LocalName = 14, /// <summary>The name of a method.</summary> MethodName = 15, /// <summary>The name of a module.</summary> ModuleName = 16, /// <summary>The name of a namespace.</summary> NamespaceName = 17, /// <summary>The symbol of an operator (e.g. "+").</summary> Operator = 18, /// <summary>The name of a parameter.</summary> ParameterName = 19, /// <summary>The name of a property.</summary> PropertyName = 20, /// <summary>A punctuation character (e.g. "(", ".", ",") other than an <see cref="Operator"/>.</summary> Punctuation = 21, /// <summary>A single space character.</summary> Space = 22, /// <summary>The name of a struct (structure in Visual Basic).</summary> StructName = 23, /// <summary>A keyword-like part for anonymous types (not actually a keyword).</summary> AnonymousTypeIndicator = 24, /// <summary>An unclassified part.</summary> /// <remarks>Never returned - only set in user-constructed parts.</remarks> Text = 25, /// <summary>The name of a type parameter.</summary> TypeParameterName = 26, /// <summary>The name of a query range variable.</summary> RangeVariableName = 27, /// <summary>The name of an enum member.</summary> EnumMemberName = 28, /// <summary>The name of a reduced extension method.</summary> /// <remarks> /// When an extension method is in it's non-reduced form it will be will be marked as MethodName. /// </remarks> ExtensionMethodName = 29, /// <summary>The name of a field or local constant.</summary> ConstantName = 30, /// <summary>The name of a record class.</summary> RecordClassName = 31, /// <summary>The name of a record struct.</summary> RecordStructName = 32, } internal static class InternalSymbolDisplayPartKind { private const SymbolDisplayPartKind @base = SymbolDisplayPartKind.RecordStructName + 1; public const SymbolDisplayPartKind Arity = @base + 0; public const SymbolDisplayPartKind Other = @base + 1; } internal static partial class EnumBounds { internal static bool IsValid(this SymbolDisplayPartKind value) { return (value >= SymbolDisplayPartKind.AliasName && value <= SymbolDisplayPartKind.RecordStructName) || (value >= InternalSymbolDisplayPartKind.Arity && value <= InternalSymbolDisplayPartKind.Other); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Interactive/HostTest/StressTests.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. extern alias InteractiveHost; using System; using System.Diagnostics; using System.Globalization; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; public sealed class StressTests { [Fact] public async Task TestKill() { for (int sleep = 0; sleep < 20; sleep++) { await TestKillAfterAsync(sleep).ConfigureAwait(false); } } private async Task TestKillAfterAsync(int milliseconds) { using var host = new InteractiveHost(typeof(CSharpReplServiceProvider), ".", millisecondsTimeout: 1, joinOutputWritingThreadsOnDisposal: true); var options = InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Desktop64); host.InteractiveHostProcessCreated += new Action<Process>(proc => { _ = Task.Run(async () => { await Task.Delay(milliseconds).ConfigureAwait(false); try { proc.Kill(); } catch { } }); }); await host.ResetAsync(options).ConfigureAwait(false); for (int j = 0; j < 10; j++) { await host.ExecuteAsync("1+1").ConfigureAwait(false); } } } }
// 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. extern alias InteractiveHost; using System; using System.Diagnostics; using System.Globalization; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; public sealed class StressTests { [Fact] public async Task TestKill() { for (int sleep = 0; sleep < 20; sleep++) { await TestKillAfterAsync(sleep).ConfigureAwait(false); } } private async Task TestKillAfterAsync(int milliseconds) { using var host = new InteractiveHost(typeof(CSharpReplServiceProvider), ".", millisecondsTimeout: 1, joinOutputWritingThreadsOnDisposal: true); var options = InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Desktop64); host.InteractiveHostProcessCreated += new Action<Process>(proc => { _ = Task.Run(async () => { await Task.Delay(milliseconds).ConfigureAwait(false); try { proc.Kill(); } catch { } }); }); await host.ResetAsync(options).ConfigureAwait(false); for (int j = 0; j < 10; j++) { await host.ExecuteAsync("1+1").ConfigureAwait(false); } } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Portable/Symbols/Source/ImplementsHelper.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.Collections.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Methods, Properties, and Events all have implements clauses and need to handle interface ''' implementation. This module has helper methods and extensions for sharing by multiple ''' symbol types. ''' </summary> ''' <remarks></remarks> Friend Module ImplementsHelper ' Given a property, method, or event symbol, get the explicitly implemented symbols Public Function GetExplicitInterfaceImplementations(member As Symbol) As ImmutableArray(Of Symbol) Select Case member.Kind Case SymbolKind.Method Return StaticCast(Of Symbol).From(DirectCast(member, MethodSymbol).ExplicitInterfaceImplementations) Case SymbolKind.Property Return StaticCast(Of Symbol).From(DirectCast(member, PropertySymbol).ExplicitInterfaceImplementations) Case SymbolKind.Event Return StaticCast(Of Symbol).From(DirectCast(member, EventSymbol).ExplicitInterfaceImplementations) Case Else Return ImmutableArray(Of Symbol).Empty End Select End Function ' Given an implementing symbol, and an implemented symbol, get the location of the ' syntax in the implements clause that matches that implemented symbol. Should only use for ' symbols from source. ' ' Used for error reporting. Public Function GetImplementingLocation(sourceSym As Symbol, implementedSym As Symbol) As Location Debug.Assert(GetExplicitInterfaceImplementations(sourceSym).Contains(implementedSym)) Dim sourceMethod = TryCast(sourceSym, SourceMethodSymbol) If sourceMethod IsNot Nothing Then Return sourceMethod.GetImplementingLocation(DirectCast(implementedSym, MethodSymbol)) End If Dim sourceProperty = TryCast(sourceSym, SourcePropertySymbol) If sourceProperty IsNot Nothing Then Return sourceProperty.GetImplementingLocation(DirectCast(implementedSym, PropertySymbol)) End If Dim sourceEvent = TryCast(sourceSym, SourceEventSymbol) If sourceEvent IsNot Nothing Then Return sourceEvent.GetImplementingLocation(DirectCast(implementedSym, EventSymbol)) End If ' Should always pass source symbol into this function Throw ExceptionUtilities.Unreachable End Function ' Given an implements clause syntax on an implementing symbol, and an implemented symbol, find and return the particular name ' syntax in the implements clause that matches that implemented symbol, or Nothing if none match. ' ' Used for error reporting. Public Function FindImplementingSyntax(Of TSymbol As Symbol)(implementsClause As ImplementsClauseSyntax, implementingSym As TSymbol, implementedSym As TSymbol, container As SourceMemberContainerTypeSymbol, binder As Binder) As QualifiedNameSyntax Debug.Assert(implementedSym IsNot Nothing) Dim dummyResultKind As LookupResultKind ' Bind each syntax again and compare them. For Each implementedMethodSyntax As QualifiedNameSyntax In implementsClause.InterfaceMembers ' don't care about diagnostics Dim implementedMethod As TSymbol = FindExplicitlyImplementedMember(implementingSym, container, implementedMethodSyntax, binder, BindingDiagnosticBag.Discarded, Nothing, dummyResultKind) If implementedMethod = implementedSym Then Return implementedMethodSyntax End If Next Return Nothing End Function ' Given a symbol in the process of being constructed, bind the Implements clause ' on it and diagnose any errors. Returns the list of implemented members. Public Function ProcessImplementsClause(Of TSymbol As Symbol)(implementsClause As ImplementsClauseSyntax, implementingSym As TSymbol, container As SourceMemberContainerTypeSymbol, binder As Binder, diagBag As BindingDiagnosticBag) As ImmutableArray(Of TSymbol) Debug.Assert(implementsClause IsNot Nothing) If container.IsInterface Then ' Members in interfaces cannot have an implements clause (each member has its own error code) Dim errorid As ERRID If implementingSym.Kind = SymbolKind.Method Then errorid = ERRID.ERR_BadInterfaceMethodFlags1 ElseIf implementingSym.Kind = SymbolKind.Property Then errorid = ERRID.ERR_BadInterfacePropertyFlags1 Else errorid = ERRID.ERR_InterfaceCantUseEventSpecifier1 End If Binder.ReportDiagnostic(diagBag, implementsClause, errorid, implementsClause.ImplementsKeyword.ToString()) Return ImmutableArray(Of TSymbol).Empty ElseIf container.IsModuleType Then ' Methods in Std Modules can't implement interfaces Binder.ReportDiagnostic(diagBag, implementsClause.ImplementsKeyword, ERRID.ERR_ModuleMemberCantImplement) Return ImmutableArray(Of TSymbol).Empty Else ' Process the IMPLEMENTS lists Dim implementedMembers As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance() Dim dummyResultKind As LookupResultKind Dim firstImplementedMemberIsWindowsRuntimeEvent As ThreeState = ThreeState.Unknown Dim implementingSymIsEvent = (implementingSym.Kind = SymbolKind.Event) For Each implementedMemberSyntax As QualifiedNameSyntax In implementsClause.InterfaceMembers Dim implementedMember As TSymbol = FindExplicitlyImplementedMember(implementingSym, container, implementedMemberSyntax, binder, diagBag, Nothing, dummyResultKind) If implementedMember IsNot Nothing Then implementedMembers.Add(implementedMember) ' Process Obsolete attribute on implements clause Binder.ReportDiagnosticsIfObsolete(diagBag, implementingSym, implementedMember, implementsClause) If implementingSymIsEvent Then Debug.Assert(implementedMember.Kind = SymbolKind.Event) If Not firstImplementedMemberIsWindowsRuntimeEvent.HasValue() Then firstImplementedMemberIsWindowsRuntimeEvent = TryCast(implementedMember, EventSymbol).IsWindowsRuntimeEvent.ToThreeState() Else Dim currIsWinRT As Boolean = TryCast(implementedMember, EventSymbol).IsWindowsRuntimeEvent Dim firstIsWinRT As Boolean = firstImplementedMemberIsWindowsRuntimeEvent.Value() If currIsWinRT <> firstIsWinRT Then Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_MixingWinRTAndNETEvents, CustomSymbolDisplayFormatter.ShortErrorName(implementingSym), CustomSymbolDisplayFormatter.QualifiedName(If(firstIsWinRT, implementedMembers(0), implementedMember)), CustomSymbolDisplayFormatter.QualifiedName(If(firstIsWinRT, implementedMember, implementedMembers(0)))) End If End If End If End If Next Return implementedMembers.ToImmutableAndFree() End If End Function ''' <summary> ''' Find the implemented method denoted by "implementedMemberSyntax" that matches implementingSym. ''' Returns the implemented method, or Nothing if none. ''' ''' Also stores into "candidateSymbols" (if not Nothing) and resultKind the symbols and result kind that ''' should be used for semantic model purposes. ''' </summary> Public Function FindExplicitlyImplementedMember(Of TSymbol As Symbol)(implementingSym As TSymbol, containingType As NamedTypeSymbol, implementedMemberSyntax As QualifiedNameSyntax, binder As Binder, diagBag As BindingDiagnosticBag, candidateSymbols As ArrayBuilder(Of Symbol), ByRef resultKind As LookupResultKind) As TSymbol resultKind = LookupResultKind.Good Dim interfaceName As NameSyntax = implementedMemberSyntax.Left Dim implementedMethodName As String = implementedMemberSyntax.Right.Identifier.ValueText Dim interfaceType As TypeSymbol = binder.BindTypeSyntax(interfaceName, diagBag) If interfaceType.IsInterfaceType() Then Dim errorReported As Boolean = False ' was an error already reported? Dim interfaceNamedType As NamedTypeSymbol = DirectCast(interfaceType, NamedTypeSymbol) If Not containingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics(interfaceNamedType).Contains(interfaceNamedType) Then ' Class doesn't implement the interface that was named Binder.ReportDiagnostic(diagBag, interfaceName, ERRID.ERR_InterfaceNotImplemented1, interfaceType) resultKind = LookupResultKind.NotReferencable errorReported = True ' continue on... End If ' Do lookup of the specified name in the interface (note it could be in a base interface thereof) Dim lookup As LookupResult = LookupResult.GetInstance() Dim foundMember As TSymbol = Nothing ' the correctly matching method we found ' NOTE(cyrusn): We pass 'IgnoreAccessibility' here to provide a better experience ' for the IDE. For correct code it won't matter (as interface members are always ' public in correct code). However, in incorrect code it makes sure we can hook up ' the implements clause to a private member. Dim options As LookupOptions = LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreAccessibility Or LookupOptions.IgnoreExtensionMethods If implementingSym.Kind = SymbolKind.Event Then options = CType(options Or LookupOptions.EventsOnly, LookupOptions) End If Dim useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagBag) binder.LookupMember(lookup, interfaceType, implementedMethodName, -1, options, useSiteInfo) If lookup.IsAmbiguous Then Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_AmbiguousImplementsMember3, implementedMethodName, implementedMethodName) If candidateSymbols IsNot Nothing Then candidateSymbols.AddRange(DirectCast(lookup.Diagnostic, AmbiguousSymbolDiagnostic).AmbiguousSymbols) End If resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.Ambiguous) errorReported = True ElseIf lookup.IsGood Then ' Check each method found to see if it matches signature of methodSym Dim candidates As ArrayBuilder(Of TSymbol) = Nothing For Each possibleMatch In lookup.Symbols Dim possibleMatchMember = TryCast(possibleMatch, TSymbol) If possibleMatchMember IsNot Nothing AndAlso possibleMatchMember.ContainingType.IsInterface AndAlso MembersAreMatchingForPurposesOfInterfaceImplementation(implementingSym, possibleMatchMember) Then If candidates Is Nothing Then candidates = ArrayBuilder(Of TSymbol).GetInstance() End If candidates.Add(possibleMatchMember) End If Next Dim candidatesCount As Integer = If(candidates IsNot Nothing, candidates.Count, 0) ' If we have more than one candidate, eliminate candidates from least derived interfaces If candidatesCount > 1 Then For i As Integer = 0 To candidates.Count - 2 Dim first As TSymbol = candidates(i) If first Is Nothing Then Continue For ' has been eliminated already End If For j As Integer = i + 1 To candidates.Count - 1 Dim second As TSymbol = candidates(j) If second Is Nothing Then Continue For ' has been eliminated already End If If second.ContainingType.ImplementsInterface(first.ContainingType, comparer:=Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then candidates(i) = Nothing candidatesCount -= 1 GoTo Next_i ElseIf first.ContainingType.ImplementsInterface(second.ContainingType, comparer:=Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then candidates(j) = Nothing candidatesCount -= 1 End If Next Next_i: Next End If ' If we still have more than one candidate, they are either from the same type (type substitution can create two methods with same signature), ' or from unrelated base interfaces If candidatesCount > 1 Then For i As Integer = 0 To candidates.Count - 2 Dim first As TSymbol = candidates(i) If first Is Nothing Then Continue For ' has been eliminated already End If If foundMember Is Nothing Then foundMember = first End If For j As Integer = i + 1 To candidates.Count - 1 Dim second As TSymbol = candidates(j) If second Is Nothing Then Continue For ' has been eliminated already End If If TypeSymbol.Equals(first.ContainingType, second.ContainingType, TypeCompareKind.ConsiderEverything) Then ' type substitution can create two methods with same signature in the same type ' report ambiguity Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_AmbiguousImplements3, CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(first.ContainingType), implementedMethodName, CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(first.ContainingType), first, second) errorReported = True resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.OverloadResolutionFailure) GoTo DoneWithErrorReporting End If Next Next Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_AmbiguousImplementsMember3, implementedMethodName, implementedMethodName) resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.Ambiguous) errorReported = True DoneWithErrorReporting: If candidateSymbols IsNot Nothing Then candidateSymbols.AddRange(lookup.Symbols) End If ElseIf candidatesCount = 1 Then For i As Integer = 0 To candidates.Count - 1 Dim first As TSymbol = candidates(i) If first Is Nothing Then Continue For ' has been eliminated already End If foundMember = first Exit For Next Else Debug.Assert(candidatesCount = 0) ' No matching members. Remember non-matching members for semantic model questions. If candidateSymbols IsNot Nothing Then candidateSymbols.AddRange(lookup.Symbols) End If resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.OverloadResolutionFailure) End If If candidates IsNot Nothing Then candidates.Free() End If If foundMember IsNot Nothing Then Dim coClassContext As Boolean = interfaceNamedType.CoClassType IsNot Nothing If coClassContext AndAlso (implementingSym.Kind = SymbolKind.Event) <> (foundMember.Kind = SymbolKind.Event) Then ' Following Dev11 implementation: in COM Interface context if the implementing symbol ' is an event and the found candidate is not (or vice versa) we just pretend we didn't ' find anything and fall back to the default error foundMember = Nothing End If If Not errorReported Then ' Further verification of found method. foundMember = ValidateImplementedMember(implementingSym, foundMember, implementedMemberSyntax, binder, diagBag, interfaceType, implementedMethodName, errorReported) End If If foundMember IsNot Nothing Then ' Record found member for semantic model questions. If candidateSymbols IsNot Nothing Then candidateSymbols.Add(foundMember) End If resultKind = LookupResult.WorseResultKind(resultKind, lookup.Kind) If Not binder.IsAccessible(foundMember, useSiteInfo) Then resultKind = LookupResult.WorseResultKind(resultKind, LookupResultKind.Inaccessible) ' we specified IgnoreAccessibility above. Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, binder.GetInaccessibleErrorInfo(foundMember)) ElseIf foundMember.Kind = SymbolKind.Property Then Dim [property] = DirectCast(DirectCast(foundMember, Symbol), PropertySymbol) Dim accessorToCheck As MethodSymbol = [property].GetMethod If accessorToCheck Is Nothing OrElse accessorToCheck.DeclaredAccessibility = [property].DeclaredAccessibility OrElse Not accessorToCheck.RequiresImplementation() Then accessorToCheck = [property].SetMethod End If If accessorToCheck IsNot Nothing AndAlso accessorToCheck.DeclaredAccessibility <> [property].DeclaredAccessibility AndAlso accessorToCheck.RequiresImplementation() AndAlso Not binder.IsAccessible(accessorToCheck, useSiteInfo) Then Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, binder.GetInaccessibleErrorInfo(accessorToCheck)) End If End If End If End If End If diagBag.Add(interfaceName, useSiteInfo) lookup.Free() If foundMember Is Nothing And Not errorReported Then ' Didn't find a method (or it was otherwise bad in some way) Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_IdentNotMemberOfInterface4, CustomSymbolDisplayFormatter.ShortErrorName(implementingSym), implementedMethodName, implementingSym.GetKindText(), CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(interfaceType)) End If Return foundMember ElseIf interfaceType.TypeKind = TypeKind.Error Then ' BindType already reported an error, so don't report another one Return Nothing Else ' type is some other type rather than an interface Binder.ReportDiagnostic(diagBag, interfaceName, ERRID.ERR_BadImplementsType) Return Nothing End If End Function ''' <summary> ''' Does 'implementingSym' match 'implementedSym' well enough to be considered a match for interface implementation? ''' </summary> Private Function MembersAreMatchingForPurposesOfInterfaceImplementation(implementingSym As Symbol, implementedSym As Symbol) As Boolean Return MembersAreMatching(implementingSym, implementedSym, Not SymbolComparisonResults.MismatchesForExplicitInterfaceImplementations, EventSignatureComparer.ExplicitEventImplementationComparer) End Function Private Function MembersHaveMatchingTupleNames(implementingSym As Symbol, implementedSym As Symbol) As Boolean Return MembersAreMatching(implementingSym, implementedSym, SymbolComparisonResults.TupleNamesMismatch, EventSignatureComparer.ExplicitEventImplementationWithTupleNamesComparer) End Function Private Function MembersAreMatching(implementingSym As Symbol, implementedSym As Symbol, comparisons As SymbolComparisonResults, eventComparer As EventSignatureComparer) As Boolean Debug.Assert(implementingSym.Kind = implementedSym.Kind) Select Case implementingSym.Kind Case SymbolKind.Method Dim results = MethodSignatureComparer.DetailedCompare(DirectCast(implementedSym, MethodSymbol), DirectCast(implementingSym, MethodSymbol), comparisons, comparisons) Return (results = 0) Case SymbolKind.Property Dim results = PropertySignatureComparer.DetailedCompare(DirectCast(implementedSym, PropertySymbol), DirectCast(implementingSym, PropertySymbol), comparisons, comparisons) Return (results = 0) Case SymbolKind.Event Return eventComparer.Equals(DirectCast(implementedSym, EventSymbol), DirectCast(implementingSym, EventSymbol)) Case Else Throw ExceptionUtilities.UnexpectedValue(implementingSym.Kind) End Select End Function ''' <summary> ''' Perform additional validate of implementedSym and issue diagnostics. ''' Return "implementedSym" if the symbol table should record implementedSym as the implemented ''' symbol (even if diagnostics were issues). Returns Nothing if the code should not treat ''' implementedSym as the implemented symbol. ''' </summary> Private Function ValidateImplementedMember(Of TSymbol As Symbol)(implementingSym As TSymbol, implementedSym As TSymbol, implementedMemberSyntax As QualifiedNameSyntax, binder As Binder, diagBag As BindingDiagnosticBag, interfaceType As TypeSymbol, implementedMethodName As String, ByRef errorReported As Boolean) As TSymbol If Not implementedSym.RequiresImplementation() Then ' TODO: Perhaps give ERR_CantImplementNonVirtual3 like Dev10. But, this message seems more ' TODO: confusing than useful, so for now, just treat it like a method that doesn't exist. Return Nothing End If ' Validate that implementing property implements all accessors of the implemented property If implementedSym.Kind = SymbolKind.Property Then Dim implementedProperty As PropertySymbol = TryCast(implementedSym, PropertySymbol) Dim implementedPropertyGetMethod As MethodSymbol = implementedProperty.GetMethod If Not implementedPropertyGetMethod?.RequiresImplementation() Then implementedPropertyGetMethod = Nothing End If Dim implementedPropertySetMethod As MethodSymbol = implementedProperty.SetMethod If Not implementedPropertySetMethod?.RequiresImplementation() Then implementedPropertySetMethod = Nothing End If Dim implementingProperty As PropertySymbol = TryCast(implementingSym, PropertySymbol) If (implementedPropertyGetMethod IsNot Nothing AndAlso implementingProperty.GetMethod Is Nothing) OrElse (implementedPropertySetMethod IsNot Nothing AndAlso implementingProperty.SetMethod Is Nothing) Then ' "'{0}' cannot be implemented by a {1} property." Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_PropertyDoesntImplementAllAccessors, implementedProperty, implementingProperty.GetPropertyKindText()) errorReported = True ElseIf ((implementedPropertyGetMethod Is Nothing) Xor (implementedPropertySetMethod Is Nothing)) AndAlso implementingProperty.GetMethod IsNot Nothing AndAlso implementingProperty.SetMethod IsNot Nothing Then errorReported = errorReported Or Not InternalSyntax.Parser.CheckFeatureAvailability(diagBag, implementedMemberSyntax.GetLocation(), DirectCast(implementedMemberSyntax.SyntaxTree, VisualBasicSyntaxTree).Options.LanguageVersion, InternalSyntax.Feature.ImplementingReadonlyOrWriteonlyPropertyWithReadwrite) End If If implementedPropertySetMethod?.IsInitOnly <> implementingProperty.SetMethod?.IsInitOnly Then Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_PropertyDoesntImplementInitOnly, implementedProperty) errorReported = True End If End If If implementedSym IsNot Nothing AndAlso implementingSym.ContainsTupleNames() AndAlso Not MembersHaveMatchingTupleNames(implementingSym, implementedSym) Then ' it is ok to implement with no tuple names, for compatibility with VB 14, but otherwise names should match Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_ImplementingInterfaceWithDifferentTupleNames5, CustomSymbolDisplayFormatter.ShortErrorName(implementingSym), implementingSym.GetKindText(), implementedMethodName, CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(interfaceType), implementingSym, implementedSym) errorReported = True End If ' TODO: If implementing event, check that delegate types are consistent, or maybe set the delegate type. See Dev10 compiler ' TODO: in ImplementsSemantics.cpp, Bindable::BindImplements. ' Method type parameter constraints are validated later, in ValidateImplementedMethodConstraints, ' after the ExplicitInterfaceImplementations property has been set on the implementing method. Return implementedSym End Function ''' <summary> ''' Validate method type parameter constraints. This is handled outside ''' of ValidateImplementedMember because that method is invoked ''' while computing the ExplicitInterfaceImplementations value on the ''' implementing method, but method type parameters rely on the value ''' of ExplicitInterfaceImplementations to determine constraints correctly. ''' </summary> Public Sub ValidateImplementedMethodConstraints(implementingMethod As SourceMethodSymbol, implementedMethod As MethodSymbol, diagBag As BindingDiagnosticBag) If Not MethodSignatureComparer.HaveSameConstraints(implementedMethod, implementingMethod) Then ' "'{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints." Dim loc = implementingMethod.GetImplementingLocation(implementedMethod) diagBag.Add( ErrorFactory.ErrorInfo(ERRID.ERR_ImplementsWithConstraintMismatch3, implementingMethod, implementedMethod.ContainingType, implementedMethod), loc) End If End Sub ''' <summary> ''' Performs interface mapping to determine which symbol in this type or a base type ''' actually implements a particular interface member. ''' </summary> ''' <typeparam name="TSymbol">MethodSymbol or PropertySymbol or EventSymbol (an interface member).</typeparam> ''' <param name="interfaceMember">A non-null member on an interface type.</param> ''' <param name="implementingType">The type implementing the interface member.</param> ''' <param name="comparer">A comparer for comparing signatures of TSymbol according to metadata implementation rules.</param> ''' <returns>The implementing member or Nothing, if there isn't one.</returns> Public Function ComputeImplementationForInterfaceMember(Of TSymbol As Symbol)(interfaceMember As TSymbol, implementingType As TypeSymbol, comparer As IEqualityComparer(Of TSymbol)) As TSymbol Debug.Assert(TypeOf interfaceMember Is PropertySymbol OrElse TypeOf interfaceMember Is MethodSymbol OrElse TypeOf interfaceMember Is EventSymbol) Dim interfaceType As NamedTypeSymbol = interfaceMember.ContainingType Debug.Assert(interfaceType IsNot Nothing AndAlso interfaceType.IsInterface) Dim seenMDTypeDeclaringInterface As Boolean = False Dim currType As TypeSymbol = implementingType ' Go up the inheritance chain, looking for an implementation of the member. While currType IsNot Nothing ' First, check for explicit interface implementation. Dim currTypeExplicitImpl As MultiDictionary(Of Symbol, Symbol).ValueSet = currType.ExplicitInterfaceImplementationMap(interfaceMember) If currTypeExplicitImpl.Count = 1 Then Return DirectCast(currTypeExplicitImpl.Single(), TSymbol) ElseIf currTypeExplicitImpl.Count > 1 Then Return Nothing End If ' VB only supports explicit interface implementation, but for the purpose of finding implementation, we must ' check implicit implementation for members from metadata. We only want to consider metadata implementations ' if a metadata implementation (or a derived metadata implementation) actually implements the given interface ' (not a derived interface), since this is the metadata rule from Partition II, section 12.2. ' ' Consider: ' Interface IGoo ' from metadata ' Sub Goo() ' Class A ' from metadata ' Public Sub Goo() ' Class B: Inherits A: Implements IGoo ' from metadata ' Class C: Inherits B ' from metadata ' Public Shadows Sub Goo() ' Class D: Inherits C: Implements IGoo ' from source ' In this case, A.Goo is the correct implementation of IGoo.Goo within D. ' NOTE: Ideally, we'd like to distinguish between the "current" compilation and other assemblies ' (including other compilations), rather than source and metadata, but there are two reasons that ' that won't work in this case: ' 1) We really don't want consumers of the API to have to pass in the current compilation when ' they ask questions about interface implementation. ' 2) NamedTypeSymbol.Interfaces does not round-trip in the presence of implicit interface ' implementations. As in dev11, we drop interfaces from the interface list if any of their ' members are implemented in a base type (so that CLR implicit implementation will pick the ' same method as the VB language). If Not currType.Dangerous_IsFromSomeCompilationIncludingRetargeting AndAlso currType.InterfacesNoUseSiteDiagnostics.Contains(interfaceType, EqualsIgnoringComparer.InstanceCLRSignatureCompare) Then seenMDTypeDeclaringInterface = True End If If seenMDTypeDeclaringInterface Then 'check for implicit impls (name must match) Dim currTypeImplicitImpl As TSymbol currTypeImplicitImpl = FindImplicitImplementationDeclaredInType(interfaceMember, currType, comparer) If currTypeImplicitImpl IsNot Nothing Then Return currTypeImplicitImpl End If End If currType = currType.BaseTypeNoUseSiteDiagnostics End While Return Nothing End Function ''' <summary> ''' Search the declared methods of a type for one that could be an implicit implementation ''' of a given interface method (depending on interface declarations). It is assumed that the implementing ''' type is not a source type. ''' </summary> ''' <typeparam name="TSymbol">MethodSymbol or PropertySymbol or EventSymbol (an interface member).</typeparam> ''' <param name="interfaceMember">The interface member being implemented.</param> ''' <param name="currType">The type on which we are looking for a declared implementation of the interface method.</param> ''' <param name="comparer">A comparer for comparing signatures of TSymbol according to metadata implementation rules.</param> Private Function FindImplicitImplementationDeclaredInType(Of TSymbol As Symbol)(interfaceMember As TSymbol, currType As TypeSymbol, comparer As IEqualityComparer(Of TSymbol)) As TSymbol ' Debug.Assert(Not currType.Dangerous_IsFromSomeCompilationIncludingRetargeting) For Each member In currType.GetMembers(interfaceMember.Name) If member.DeclaredAccessibility = Accessibility.Public AndAlso Not member.IsShared AndAlso TypeOf member Is TSymbol AndAlso comparer.Equals(interfaceMember, DirectCast(member, TSymbol)) Then Return DirectCast(member, TSymbol) End If Next Return Nothing End Function ''' <summary> ''' Given a set of explicit interface implementations that are undergoing substitution, return the substituted versions. ''' </summary> ''' <typeparam name="TSymbol">Type of the interface members (Method, Property, Event)</typeparam> ''' <param name="unsubstitutedImplementations">The ROA of members that are being implemented</param> ''' <param name="substitution">The type substitution</param> ''' <returns>The substituted members.</returns> Public Function SubstituteExplicitInterfaceImplementations(Of TSymbol As Symbol)(unsubstitutedImplementations As ImmutableArray(Of TSymbol), substitution As TypeSubstitution) As ImmutableArray(Of TSymbol) If unsubstitutedImplementations.Length = 0 Then Return ImmutableArray(Of TSymbol).Empty Else Dim substitutedImplementations(0 To unsubstitutedImplementations.Length - 1) As TSymbol For i As Integer = 0 To unsubstitutedImplementations.Length - 1 Dim unsubstitutedMember As TSymbol = unsubstitutedImplementations(i) Dim unsubstitutedInterfaceType = unsubstitutedMember.ContainingType substitutedImplementations(i) = unsubstitutedImplementations(i) ' default: no substitution necessary If unsubstitutedInterfaceType.IsGenericType Then Dim substitutedInterfaceType = TryCast(unsubstitutedInterfaceType.InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly(), SubstitutedNamedType) If substitutedInterfaceType IsNot Nothing Then ' Get the substituted version of the member substitutedImplementations(i) = DirectCast(substitutedInterfaceType.GetMemberForDefinition(unsubstitutedMember.OriginalDefinition), TSymbol) End If End If Next Return ImmutableArray.Create(Of TSymbol)(substitutedImplementations) End If End Function End Module 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.Collections.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Methods, Properties, and Events all have implements clauses and need to handle interface ''' implementation. This module has helper methods and extensions for sharing by multiple ''' symbol types. ''' </summary> ''' <remarks></remarks> Friend Module ImplementsHelper ' Given a property, method, or event symbol, get the explicitly implemented symbols Public Function GetExplicitInterfaceImplementations(member As Symbol) As ImmutableArray(Of Symbol) Select Case member.Kind Case SymbolKind.Method Return StaticCast(Of Symbol).From(DirectCast(member, MethodSymbol).ExplicitInterfaceImplementations) Case SymbolKind.Property Return StaticCast(Of Symbol).From(DirectCast(member, PropertySymbol).ExplicitInterfaceImplementations) Case SymbolKind.Event Return StaticCast(Of Symbol).From(DirectCast(member, EventSymbol).ExplicitInterfaceImplementations) Case Else Return ImmutableArray(Of Symbol).Empty End Select End Function ' Given an implementing symbol, and an implemented symbol, get the location of the ' syntax in the implements clause that matches that implemented symbol. Should only use for ' symbols from source. ' ' Used for error reporting. Public Function GetImplementingLocation(sourceSym As Symbol, implementedSym As Symbol) As Location Debug.Assert(GetExplicitInterfaceImplementations(sourceSym).Contains(implementedSym)) Dim sourceMethod = TryCast(sourceSym, SourceMethodSymbol) If sourceMethod IsNot Nothing Then Return sourceMethod.GetImplementingLocation(DirectCast(implementedSym, MethodSymbol)) End If Dim sourceProperty = TryCast(sourceSym, SourcePropertySymbol) If sourceProperty IsNot Nothing Then Return sourceProperty.GetImplementingLocation(DirectCast(implementedSym, PropertySymbol)) End If Dim sourceEvent = TryCast(sourceSym, SourceEventSymbol) If sourceEvent IsNot Nothing Then Return sourceEvent.GetImplementingLocation(DirectCast(implementedSym, EventSymbol)) End If ' Should always pass source symbol into this function Throw ExceptionUtilities.Unreachable End Function ' Given an implements clause syntax on an implementing symbol, and an implemented symbol, find and return the particular name ' syntax in the implements clause that matches that implemented symbol, or Nothing if none match. ' ' Used for error reporting. Public Function FindImplementingSyntax(Of TSymbol As Symbol)(implementsClause As ImplementsClauseSyntax, implementingSym As TSymbol, implementedSym As TSymbol, container As SourceMemberContainerTypeSymbol, binder As Binder) As QualifiedNameSyntax Debug.Assert(implementedSym IsNot Nothing) Dim dummyResultKind As LookupResultKind ' Bind each syntax again and compare them. For Each implementedMethodSyntax As QualifiedNameSyntax In implementsClause.InterfaceMembers ' don't care about diagnostics Dim implementedMethod As TSymbol = FindExplicitlyImplementedMember(implementingSym, container, implementedMethodSyntax, binder, BindingDiagnosticBag.Discarded, Nothing, dummyResultKind) If implementedMethod = implementedSym Then Return implementedMethodSyntax End If Next Return Nothing End Function ' Given a symbol in the process of being constructed, bind the Implements clause ' on it and diagnose any errors. Returns the list of implemented members. Public Function ProcessImplementsClause(Of TSymbol As Symbol)(implementsClause As ImplementsClauseSyntax, implementingSym As TSymbol, container As SourceMemberContainerTypeSymbol, binder As Binder, diagBag As BindingDiagnosticBag) As ImmutableArray(Of TSymbol) Debug.Assert(implementsClause IsNot Nothing) If container.IsInterface Then ' Members in interfaces cannot have an implements clause (each member has its own error code) Dim errorid As ERRID If implementingSym.Kind = SymbolKind.Method Then errorid = ERRID.ERR_BadInterfaceMethodFlags1 ElseIf implementingSym.Kind = SymbolKind.Property Then errorid = ERRID.ERR_BadInterfacePropertyFlags1 Else errorid = ERRID.ERR_InterfaceCantUseEventSpecifier1 End If Binder.ReportDiagnostic(diagBag, implementsClause, errorid, implementsClause.ImplementsKeyword.ToString()) Return ImmutableArray(Of TSymbol).Empty ElseIf container.IsModuleType Then ' Methods in Std Modules can't implement interfaces Binder.ReportDiagnostic(diagBag, implementsClause.ImplementsKeyword, ERRID.ERR_ModuleMemberCantImplement) Return ImmutableArray(Of TSymbol).Empty Else ' Process the IMPLEMENTS lists Dim implementedMembers As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance() Dim dummyResultKind As LookupResultKind Dim firstImplementedMemberIsWindowsRuntimeEvent As ThreeState = ThreeState.Unknown Dim implementingSymIsEvent = (implementingSym.Kind = SymbolKind.Event) For Each implementedMemberSyntax As QualifiedNameSyntax In implementsClause.InterfaceMembers Dim implementedMember As TSymbol = FindExplicitlyImplementedMember(implementingSym, container, implementedMemberSyntax, binder, diagBag, Nothing, dummyResultKind) If implementedMember IsNot Nothing Then implementedMembers.Add(implementedMember) ' Process Obsolete attribute on implements clause Binder.ReportDiagnosticsIfObsolete(diagBag, implementingSym, implementedMember, implementsClause) If implementingSymIsEvent Then Debug.Assert(implementedMember.Kind = SymbolKind.Event) If Not firstImplementedMemberIsWindowsRuntimeEvent.HasValue() Then firstImplementedMemberIsWindowsRuntimeEvent = TryCast(implementedMember, EventSymbol).IsWindowsRuntimeEvent.ToThreeState() Else Dim currIsWinRT As Boolean = TryCast(implementedMember, EventSymbol).IsWindowsRuntimeEvent Dim firstIsWinRT As Boolean = firstImplementedMemberIsWindowsRuntimeEvent.Value() If currIsWinRT <> firstIsWinRT Then Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_MixingWinRTAndNETEvents, CustomSymbolDisplayFormatter.ShortErrorName(implementingSym), CustomSymbolDisplayFormatter.QualifiedName(If(firstIsWinRT, implementedMembers(0), implementedMember)), CustomSymbolDisplayFormatter.QualifiedName(If(firstIsWinRT, implementedMember, implementedMembers(0)))) End If End If End If End If Next Return implementedMembers.ToImmutableAndFree() End If End Function ''' <summary> ''' Find the implemented method denoted by "implementedMemberSyntax" that matches implementingSym. ''' Returns the implemented method, or Nothing if none. ''' ''' Also stores into "candidateSymbols" (if not Nothing) and resultKind the symbols and result kind that ''' should be used for semantic model purposes. ''' </summary> Public Function FindExplicitlyImplementedMember(Of TSymbol As Symbol)(implementingSym As TSymbol, containingType As NamedTypeSymbol, implementedMemberSyntax As QualifiedNameSyntax, binder As Binder, diagBag As BindingDiagnosticBag, candidateSymbols As ArrayBuilder(Of Symbol), ByRef resultKind As LookupResultKind) As TSymbol resultKind = LookupResultKind.Good Dim interfaceName As NameSyntax = implementedMemberSyntax.Left Dim implementedMethodName As String = implementedMemberSyntax.Right.Identifier.ValueText Dim interfaceType As TypeSymbol = binder.BindTypeSyntax(interfaceName, diagBag) If interfaceType.IsInterfaceType() Then Dim errorReported As Boolean = False ' was an error already reported? Dim interfaceNamedType As NamedTypeSymbol = DirectCast(interfaceType, NamedTypeSymbol) If Not containingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics(interfaceNamedType).Contains(interfaceNamedType) Then ' Class doesn't implement the interface that was named Binder.ReportDiagnostic(diagBag, interfaceName, ERRID.ERR_InterfaceNotImplemented1, interfaceType) resultKind = LookupResultKind.NotReferencable errorReported = True ' continue on... End If ' Do lookup of the specified name in the interface (note it could be in a base interface thereof) Dim lookup As LookupResult = LookupResult.GetInstance() Dim foundMember As TSymbol = Nothing ' the correctly matching method we found ' NOTE(cyrusn): We pass 'IgnoreAccessibility' here to provide a better experience ' for the IDE. For correct code it won't matter (as interface members are always ' public in correct code). However, in incorrect code it makes sure we can hook up ' the implements clause to a private member. Dim options As LookupOptions = LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreAccessibility Or LookupOptions.IgnoreExtensionMethods If implementingSym.Kind = SymbolKind.Event Then options = CType(options Or LookupOptions.EventsOnly, LookupOptions) End If Dim useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagBag) binder.LookupMember(lookup, interfaceType, implementedMethodName, -1, options, useSiteInfo) If lookup.IsAmbiguous Then Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_AmbiguousImplementsMember3, implementedMethodName, implementedMethodName) If candidateSymbols IsNot Nothing Then candidateSymbols.AddRange(DirectCast(lookup.Diagnostic, AmbiguousSymbolDiagnostic).AmbiguousSymbols) End If resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.Ambiguous) errorReported = True ElseIf lookup.IsGood Then ' Check each method found to see if it matches signature of methodSym Dim candidates As ArrayBuilder(Of TSymbol) = Nothing For Each possibleMatch In lookup.Symbols Dim possibleMatchMember = TryCast(possibleMatch, TSymbol) If possibleMatchMember IsNot Nothing AndAlso possibleMatchMember.ContainingType.IsInterface AndAlso MembersAreMatchingForPurposesOfInterfaceImplementation(implementingSym, possibleMatchMember) Then If candidates Is Nothing Then candidates = ArrayBuilder(Of TSymbol).GetInstance() End If candidates.Add(possibleMatchMember) End If Next Dim candidatesCount As Integer = If(candidates IsNot Nothing, candidates.Count, 0) ' If we have more than one candidate, eliminate candidates from least derived interfaces If candidatesCount > 1 Then For i As Integer = 0 To candidates.Count - 2 Dim first As TSymbol = candidates(i) If first Is Nothing Then Continue For ' has been eliminated already End If For j As Integer = i + 1 To candidates.Count - 1 Dim second As TSymbol = candidates(j) If second Is Nothing Then Continue For ' has been eliminated already End If If second.ContainingType.ImplementsInterface(first.ContainingType, comparer:=Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then candidates(i) = Nothing candidatesCount -= 1 GoTo Next_i ElseIf first.ContainingType.ImplementsInterface(second.ContainingType, comparer:=Nothing, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then candidates(j) = Nothing candidatesCount -= 1 End If Next Next_i: Next End If ' If we still have more than one candidate, they are either from the same type (type substitution can create two methods with same signature), ' or from unrelated base interfaces If candidatesCount > 1 Then For i As Integer = 0 To candidates.Count - 2 Dim first As TSymbol = candidates(i) If first Is Nothing Then Continue For ' has been eliminated already End If If foundMember Is Nothing Then foundMember = first End If For j As Integer = i + 1 To candidates.Count - 1 Dim second As TSymbol = candidates(j) If second Is Nothing Then Continue For ' has been eliminated already End If If TypeSymbol.Equals(first.ContainingType, second.ContainingType, TypeCompareKind.ConsiderEverything) Then ' type substitution can create two methods with same signature in the same type ' report ambiguity Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_AmbiguousImplements3, CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(first.ContainingType), implementedMethodName, CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(first.ContainingType), first, second) errorReported = True resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.OverloadResolutionFailure) GoTo DoneWithErrorReporting End If Next Next Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_AmbiguousImplementsMember3, implementedMethodName, implementedMethodName) resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.Ambiguous) errorReported = True DoneWithErrorReporting: If candidateSymbols IsNot Nothing Then candidateSymbols.AddRange(lookup.Symbols) End If ElseIf candidatesCount = 1 Then For i As Integer = 0 To candidates.Count - 1 Dim first As TSymbol = candidates(i) If first Is Nothing Then Continue For ' has been eliminated already End If foundMember = first Exit For Next Else Debug.Assert(candidatesCount = 0) ' No matching members. Remember non-matching members for semantic model questions. If candidateSymbols IsNot Nothing Then candidateSymbols.AddRange(lookup.Symbols) End If resultKind = LookupResult.WorseResultKind(lookup.Kind, LookupResultKind.OverloadResolutionFailure) End If If candidates IsNot Nothing Then candidates.Free() End If If foundMember IsNot Nothing Then Dim coClassContext As Boolean = interfaceNamedType.CoClassType IsNot Nothing If coClassContext AndAlso (implementingSym.Kind = SymbolKind.Event) <> (foundMember.Kind = SymbolKind.Event) Then ' Following Dev11 implementation: in COM Interface context if the implementing symbol ' is an event and the found candidate is not (or vice versa) we just pretend we didn't ' find anything and fall back to the default error foundMember = Nothing End If If Not errorReported Then ' Further verification of found method. foundMember = ValidateImplementedMember(implementingSym, foundMember, implementedMemberSyntax, binder, diagBag, interfaceType, implementedMethodName, errorReported) End If If foundMember IsNot Nothing Then ' Record found member for semantic model questions. If candidateSymbols IsNot Nothing Then candidateSymbols.Add(foundMember) End If resultKind = LookupResult.WorseResultKind(resultKind, lookup.Kind) If Not binder.IsAccessible(foundMember, useSiteInfo) Then resultKind = LookupResult.WorseResultKind(resultKind, LookupResultKind.Inaccessible) ' we specified IgnoreAccessibility above. Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, binder.GetInaccessibleErrorInfo(foundMember)) ElseIf foundMember.Kind = SymbolKind.Property Then Dim [property] = DirectCast(DirectCast(foundMember, Symbol), PropertySymbol) Dim accessorToCheck As MethodSymbol = [property].GetMethod If accessorToCheck Is Nothing OrElse accessorToCheck.DeclaredAccessibility = [property].DeclaredAccessibility OrElse Not accessorToCheck.RequiresImplementation() Then accessorToCheck = [property].SetMethod End If If accessorToCheck IsNot Nothing AndAlso accessorToCheck.DeclaredAccessibility <> [property].DeclaredAccessibility AndAlso accessorToCheck.RequiresImplementation() AndAlso Not binder.IsAccessible(accessorToCheck, useSiteInfo) Then Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, binder.GetInaccessibleErrorInfo(accessorToCheck)) End If End If End If End If End If diagBag.Add(interfaceName, useSiteInfo) lookup.Free() If foundMember Is Nothing And Not errorReported Then ' Didn't find a method (or it was otherwise bad in some way) Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_IdentNotMemberOfInterface4, CustomSymbolDisplayFormatter.ShortErrorName(implementingSym), implementedMethodName, implementingSym.GetKindText(), CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(interfaceType)) End If Return foundMember ElseIf interfaceType.TypeKind = TypeKind.Error Then ' BindType already reported an error, so don't report another one Return Nothing Else ' type is some other type rather than an interface Binder.ReportDiagnostic(diagBag, interfaceName, ERRID.ERR_BadImplementsType) Return Nothing End If End Function ''' <summary> ''' Does 'implementingSym' match 'implementedSym' well enough to be considered a match for interface implementation? ''' </summary> Private Function MembersAreMatchingForPurposesOfInterfaceImplementation(implementingSym As Symbol, implementedSym As Symbol) As Boolean Return MembersAreMatching(implementingSym, implementedSym, Not SymbolComparisonResults.MismatchesForExplicitInterfaceImplementations, EventSignatureComparer.ExplicitEventImplementationComparer) End Function Private Function MembersHaveMatchingTupleNames(implementingSym As Symbol, implementedSym As Symbol) As Boolean Return MembersAreMatching(implementingSym, implementedSym, SymbolComparisonResults.TupleNamesMismatch, EventSignatureComparer.ExplicitEventImplementationWithTupleNamesComparer) End Function Private Function MembersAreMatching(implementingSym As Symbol, implementedSym As Symbol, comparisons As SymbolComparisonResults, eventComparer As EventSignatureComparer) As Boolean Debug.Assert(implementingSym.Kind = implementedSym.Kind) Select Case implementingSym.Kind Case SymbolKind.Method Dim results = MethodSignatureComparer.DetailedCompare(DirectCast(implementedSym, MethodSymbol), DirectCast(implementingSym, MethodSymbol), comparisons, comparisons) Return (results = 0) Case SymbolKind.Property Dim results = PropertySignatureComparer.DetailedCompare(DirectCast(implementedSym, PropertySymbol), DirectCast(implementingSym, PropertySymbol), comparisons, comparisons) Return (results = 0) Case SymbolKind.Event Return eventComparer.Equals(DirectCast(implementedSym, EventSymbol), DirectCast(implementingSym, EventSymbol)) Case Else Throw ExceptionUtilities.UnexpectedValue(implementingSym.Kind) End Select End Function ''' <summary> ''' Perform additional validate of implementedSym and issue diagnostics. ''' Return "implementedSym" if the symbol table should record implementedSym as the implemented ''' symbol (even if diagnostics were issues). Returns Nothing if the code should not treat ''' implementedSym as the implemented symbol. ''' </summary> Private Function ValidateImplementedMember(Of TSymbol As Symbol)(implementingSym As TSymbol, implementedSym As TSymbol, implementedMemberSyntax As QualifiedNameSyntax, binder As Binder, diagBag As BindingDiagnosticBag, interfaceType As TypeSymbol, implementedMethodName As String, ByRef errorReported As Boolean) As TSymbol If Not implementedSym.RequiresImplementation() Then ' TODO: Perhaps give ERR_CantImplementNonVirtual3 like Dev10. But, this message seems more ' TODO: confusing than useful, so for now, just treat it like a method that doesn't exist. Return Nothing End If ' Validate that implementing property implements all accessors of the implemented property If implementedSym.Kind = SymbolKind.Property Then Dim implementedProperty As PropertySymbol = TryCast(implementedSym, PropertySymbol) Dim implementedPropertyGetMethod As MethodSymbol = implementedProperty.GetMethod If Not implementedPropertyGetMethod?.RequiresImplementation() Then implementedPropertyGetMethod = Nothing End If Dim implementedPropertySetMethod As MethodSymbol = implementedProperty.SetMethod If Not implementedPropertySetMethod?.RequiresImplementation() Then implementedPropertySetMethod = Nothing End If Dim implementingProperty As PropertySymbol = TryCast(implementingSym, PropertySymbol) If (implementedPropertyGetMethod IsNot Nothing AndAlso implementingProperty.GetMethod Is Nothing) OrElse (implementedPropertySetMethod IsNot Nothing AndAlso implementingProperty.SetMethod Is Nothing) Then ' "'{0}' cannot be implemented by a {1} property." Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_PropertyDoesntImplementAllAccessors, implementedProperty, implementingProperty.GetPropertyKindText()) errorReported = True ElseIf ((implementedPropertyGetMethod Is Nothing) Xor (implementedPropertySetMethod Is Nothing)) AndAlso implementingProperty.GetMethod IsNot Nothing AndAlso implementingProperty.SetMethod IsNot Nothing Then errorReported = errorReported Or Not InternalSyntax.Parser.CheckFeatureAvailability(diagBag, implementedMemberSyntax.GetLocation(), DirectCast(implementedMemberSyntax.SyntaxTree, VisualBasicSyntaxTree).Options.LanguageVersion, InternalSyntax.Feature.ImplementingReadonlyOrWriteonlyPropertyWithReadwrite) End If If implementedPropertySetMethod?.IsInitOnly <> implementingProperty.SetMethod?.IsInitOnly Then Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_PropertyDoesntImplementInitOnly, implementedProperty) errorReported = True End If End If If implementedSym IsNot Nothing AndAlso implementingSym.ContainsTupleNames() AndAlso Not MembersHaveMatchingTupleNames(implementingSym, implementedSym) Then ' it is ok to implement with no tuple names, for compatibility with VB 14, but otherwise names should match Binder.ReportDiagnostic(diagBag, implementedMemberSyntax, ERRID.ERR_ImplementingInterfaceWithDifferentTupleNames5, CustomSymbolDisplayFormatter.ShortErrorName(implementingSym), implementingSym.GetKindText(), implementedMethodName, CustomSymbolDisplayFormatter.ShortNameWithTypeArgs(interfaceType), implementingSym, implementedSym) errorReported = True End If ' TODO: If implementing event, check that delegate types are consistent, or maybe set the delegate type. See Dev10 compiler ' TODO: in ImplementsSemantics.cpp, Bindable::BindImplements. ' Method type parameter constraints are validated later, in ValidateImplementedMethodConstraints, ' after the ExplicitInterfaceImplementations property has been set on the implementing method. Return implementedSym End Function ''' <summary> ''' Validate method type parameter constraints. This is handled outside ''' of ValidateImplementedMember because that method is invoked ''' while computing the ExplicitInterfaceImplementations value on the ''' implementing method, but method type parameters rely on the value ''' of ExplicitInterfaceImplementations to determine constraints correctly. ''' </summary> Public Sub ValidateImplementedMethodConstraints(implementingMethod As SourceMethodSymbol, implementedMethod As MethodSymbol, diagBag As BindingDiagnosticBag) If Not MethodSignatureComparer.HaveSameConstraints(implementedMethod, implementingMethod) Then ' "'{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints." Dim loc = implementingMethod.GetImplementingLocation(implementedMethod) diagBag.Add( ErrorFactory.ErrorInfo(ERRID.ERR_ImplementsWithConstraintMismatch3, implementingMethod, implementedMethod.ContainingType, implementedMethod), loc) End If End Sub ''' <summary> ''' Performs interface mapping to determine which symbol in this type or a base type ''' actually implements a particular interface member. ''' </summary> ''' <typeparam name="TSymbol">MethodSymbol or PropertySymbol or EventSymbol (an interface member).</typeparam> ''' <param name="interfaceMember">A non-null member on an interface type.</param> ''' <param name="implementingType">The type implementing the interface member.</param> ''' <param name="comparer">A comparer for comparing signatures of TSymbol according to metadata implementation rules.</param> ''' <returns>The implementing member or Nothing, if there isn't one.</returns> Public Function ComputeImplementationForInterfaceMember(Of TSymbol As Symbol)(interfaceMember As TSymbol, implementingType As TypeSymbol, comparer As IEqualityComparer(Of TSymbol)) As TSymbol Debug.Assert(TypeOf interfaceMember Is PropertySymbol OrElse TypeOf interfaceMember Is MethodSymbol OrElse TypeOf interfaceMember Is EventSymbol) Dim interfaceType As NamedTypeSymbol = interfaceMember.ContainingType Debug.Assert(interfaceType IsNot Nothing AndAlso interfaceType.IsInterface) Dim seenMDTypeDeclaringInterface As Boolean = False Dim currType As TypeSymbol = implementingType ' Go up the inheritance chain, looking for an implementation of the member. While currType IsNot Nothing ' First, check for explicit interface implementation. Dim currTypeExplicitImpl As MultiDictionary(Of Symbol, Symbol).ValueSet = currType.ExplicitInterfaceImplementationMap(interfaceMember) If currTypeExplicitImpl.Count = 1 Then Return DirectCast(currTypeExplicitImpl.Single(), TSymbol) ElseIf currTypeExplicitImpl.Count > 1 Then Return Nothing End If ' VB only supports explicit interface implementation, but for the purpose of finding implementation, we must ' check implicit implementation for members from metadata. We only want to consider metadata implementations ' if a metadata implementation (or a derived metadata implementation) actually implements the given interface ' (not a derived interface), since this is the metadata rule from Partition II, section 12.2. ' ' Consider: ' Interface IGoo ' from metadata ' Sub Goo() ' Class A ' from metadata ' Public Sub Goo() ' Class B: Inherits A: Implements IGoo ' from metadata ' Class C: Inherits B ' from metadata ' Public Shadows Sub Goo() ' Class D: Inherits C: Implements IGoo ' from source ' In this case, A.Goo is the correct implementation of IGoo.Goo within D. ' NOTE: Ideally, we'd like to distinguish between the "current" compilation and other assemblies ' (including other compilations), rather than source and metadata, but there are two reasons that ' that won't work in this case: ' 1) We really don't want consumers of the API to have to pass in the current compilation when ' they ask questions about interface implementation. ' 2) NamedTypeSymbol.Interfaces does not round-trip in the presence of implicit interface ' implementations. As in dev11, we drop interfaces from the interface list if any of their ' members are implemented in a base type (so that CLR implicit implementation will pick the ' same method as the VB language). If Not currType.Dangerous_IsFromSomeCompilationIncludingRetargeting AndAlso currType.InterfacesNoUseSiteDiagnostics.Contains(interfaceType, EqualsIgnoringComparer.InstanceCLRSignatureCompare) Then seenMDTypeDeclaringInterface = True End If If seenMDTypeDeclaringInterface Then 'check for implicit impls (name must match) Dim currTypeImplicitImpl As TSymbol currTypeImplicitImpl = FindImplicitImplementationDeclaredInType(interfaceMember, currType, comparer) If currTypeImplicitImpl IsNot Nothing Then Return currTypeImplicitImpl End If End If currType = currType.BaseTypeNoUseSiteDiagnostics End While Return Nothing End Function ''' <summary> ''' Search the declared methods of a type for one that could be an implicit implementation ''' of a given interface method (depending on interface declarations). It is assumed that the implementing ''' type is not a source type. ''' </summary> ''' <typeparam name="TSymbol">MethodSymbol or PropertySymbol or EventSymbol (an interface member).</typeparam> ''' <param name="interfaceMember">The interface member being implemented.</param> ''' <param name="currType">The type on which we are looking for a declared implementation of the interface method.</param> ''' <param name="comparer">A comparer for comparing signatures of TSymbol according to metadata implementation rules.</param> Private Function FindImplicitImplementationDeclaredInType(Of TSymbol As Symbol)(interfaceMember As TSymbol, currType As TypeSymbol, comparer As IEqualityComparer(Of TSymbol)) As TSymbol ' Debug.Assert(Not currType.Dangerous_IsFromSomeCompilationIncludingRetargeting) For Each member In currType.GetMembers(interfaceMember.Name) If member.DeclaredAccessibility = Accessibility.Public AndAlso Not member.IsShared AndAlso TypeOf member Is TSymbol AndAlso comparer.Equals(interfaceMember, DirectCast(member, TSymbol)) Then Return DirectCast(member, TSymbol) End If Next Return Nothing End Function ''' <summary> ''' Given a set of explicit interface implementations that are undergoing substitution, return the substituted versions. ''' </summary> ''' <typeparam name="TSymbol">Type of the interface members (Method, Property, Event)</typeparam> ''' <param name="unsubstitutedImplementations">The ROA of members that are being implemented</param> ''' <param name="substitution">The type substitution</param> ''' <returns>The substituted members.</returns> Public Function SubstituteExplicitInterfaceImplementations(Of TSymbol As Symbol)(unsubstitutedImplementations As ImmutableArray(Of TSymbol), substitution As TypeSubstitution) As ImmutableArray(Of TSymbol) If unsubstitutedImplementations.Length = 0 Then Return ImmutableArray(Of TSymbol).Empty Else Dim substitutedImplementations(0 To unsubstitutedImplementations.Length - 1) As TSymbol For i As Integer = 0 To unsubstitutedImplementations.Length - 1 Dim unsubstitutedMember As TSymbol = unsubstitutedImplementations(i) Dim unsubstitutedInterfaceType = unsubstitutedMember.ContainingType substitutedImplementations(i) = unsubstitutedImplementations(i) ' default: no substitution necessary If unsubstitutedInterfaceType.IsGenericType Then Dim substitutedInterfaceType = TryCast(unsubstitutedInterfaceType.InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly(), SubstitutedNamedType) If substitutedInterfaceType IsNot Nothing Then ' Get the substituted version of the member substitutedImplementations(i) = DirectCast(substitutedInterfaceType.GetMemberForDefinition(unsubstitutedMember.OriginalDefinition), TSymbol) End If End If Next Return ImmutableArray.Create(Of TSymbol)(substitutedImplementations) End If End Function End Module End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/EditorFeatures/CSharpTest/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests.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.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.EmbeddedLanguages.Common; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions { using RegexToken = EmbeddedSyntaxToken<RegexKind>; using RegexTrivia = EmbeddedSyntaxTrivia<RegexKind>; public partial class CSharpRegexParserTests { private readonly IVirtualCharService _service = CSharpVirtualCharService.Instance; private const string _statmentPrefix = "var v = "; private static SyntaxToken GetStringToken(string text) { var statement = _statmentPrefix + text; var parsedStatement = SyntaxFactory.ParseStatement(statement); var token = parsedStatement.DescendantTokens().ToArray()[3]; Assert.True(token.Kind() == SyntaxKind.StringLiteralToken); return token; } private void Test(string stringText, string expected, RegexOptions options, bool runSubTreeTests = true, bool allowIndexOutOfRange = false, bool allowNullReference = false, bool allowOutOfMemory = false, bool allowDiagnosticsMismatch = false) { var (tree, sourceText) = TryParseTree(stringText, options, conversionFailureOk: false, allowIndexOutOfRange, allowNullReference, allowOutOfMemory, allowDiagnosticsMismatch); // Tests are allowed to not run the subtree tests. This is because some // subtrees can cause the native regex parser to exhibit very bad behavior // (like not ever actually finishing compiling). if (runSubTreeTests) { TryParseSubTrees(stringText, options, allowIndexOutOfRange, allowNullReference, allowOutOfMemory, allowDiagnosticsMismatch); } const string DoubleQuoteEscaping = "\"\""; var actual = TreeToText(sourceText, tree) .Replace("\"", DoubleQuoteEscaping) .Replace("&quot;", DoubleQuoteEscaping); Assert.Equal(expected.Replace("\"", DoubleQuoteEscaping), actual); } private void TryParseSubTrees( string stringText, RegexOptions options, bool allowIndexOutOfRange, bool allowNullReference, bool allowOutOfMemory, bool allowDiagnosticsMismatch) { // Trim the input from the right and make sure tree invariants hold var current = stringText; while (current != "@\"\"" && current != "\"\"") { current = current.Substring(0, current.Length - 2) + "\""; TryParseTree(current, options, conversionFailureOk: true, allowIndexOutOfRange, allowNullReference, allowOutOfMemory, allowDiagnosticsMismatch); } // Trim the input from the left and make sure tree invariants hold current = stringText; while (current != "@\"\"" && current != "\"\"") { if (current[0] == '@') { current = "@\"" + current.Substring(3); } else { current = "\"" + current.Substring(2); } TryParseTree(current, options, conversionFailureOk: true, allowIndexOutOfRange, allowNullReference, allowOutOfMemory, allowDiagnosticsMismatch); } for (var start = stringText[0] == '@' ? 2 : 1; start < stringText.Length - 1; start++) { TryParseTree( stringText.Substring(0, start) + stringText.Substring(start + 1, stringText.Length - (start + 1)), options, conversionFailureOk: true, allowIndexOutOfRange, allowNullReference, allowOutOfMemory, allowDiagnosticsMismatch); } } private (SyntaxToken, RegexTree, VirtualCharSequence) JustParseTree( string stringText, RegexOptions options, bool conversionFailureOk) { var token = GetStringToken(stringText); var allChars = _service.TryConvertToVirtualChars(token); if (allChars.IsDefault) { Assert.True(conversionFailureOk, "Failed to convert text to token."); return (token, null, allChars); } var tree = RegexParser.TryParse(allChars, options); return (token, tree, allChars); } private (RegexTree, SourceText) TryParseTree( string stringText, RegexOptions options, bool conversionFailureOk, bool allowIndexOutOfRange, bool allowNullReference, bool allowOutOfMemeory, bool allowDiagnosticsMismatch = false) { var (token, tree, allChars) = JustParseTree(stringText, options, conversionFailureOk); if (tree == null) { Assert.True(allChars.IsDefault); return default; } CheckInvariants(tree, allChars); var sourceText = token.SyntaxTree.GetText(); var treeAndText = (tree, sourceText); Regex regex = null; try { regex = new Regex(token.ValueText, options); } catch (IndexOutOfRangeException) when (allowIndexOutOfRange) { // bug with .NET regex parser. Can happen with patterns like: (?<-0 Assert.NotEmpty(tree.Diagnostics); return treeAndText; } catch (NullReferenceException) when (allowNullReference) { // bug with .NET regex parser. can happen with patterns like: (?(?S)) return treeAndText; } catch (OutOfMemoryException) when (allowOutOfMemeory) { // bug with .NET regex parser. can happen with patterns like: a{2147483647,} return treeAndText; } catch (ArgumentException ex) { if (!allowDiagnosticsMismatch) { Assert.NotEmpty(tree.Diagnostics); // Ensure the diagnostic we emit is the same as the .NET one. Note: we can only // do this in en-US as that's the only culture where we control the text exactly // and can ensure it exactly matches Regex. We depend on localization to do a // good enough job here for other languages. if (Thread.CurrentThread.CurrentCulture.Name == "en-US") { Assert.True(tree.Diagnostics.Any(d => ex.Message.Contains(d.Message))); } } return treeAndText; } if (!tree.Diagnostics.IsEmpty && !allowDiagnosticsMismatch) { var expectedDiagnostics = CreateDiagnosticsElement(sourceText, tree); Assert.False(true, "Expected diagnostics: \r\n" + expectedDiagnostics.ToString().Replace(@"""", @"""""")); } Assert.True(regex.GetGroupNumbers().OrderBy(v => v).SequenceEqual( tree.CaptureNumbersToSpan.Keys.OrderBy(v => v).Select(v => (int)v))); Assert.True(regex.GetGroupNames().Where(v => !int.TryParse(v, out _)).OrderBy(v => v).SequenceEqual( tree.CaptureNamesToSpan.Keys.OrderBy(v => v))); return treeAndText; } private string TreeToText(SourceText text, RegexTree tree) { var element = new XElement("Tree", NodeToElement(tree.Root)); if (tree.Diagnostics.Length > 0) { element.Add(CreateDiagnosticsElement(text, tree)); } element.Add(new XElement("Captures", tree.CaptureNumbersToSpan.OrderBy(kvp => kvp.Key).Select(kvp => new XElement("Capture", new XAttribute("Name", kvp.Key), new XAttribute("Span", kvp.Value), GetTextAttribute(text, kvp.Value))), tree.CaptureNamesToSpan.OrderBy(kvp => kvp.Key).Select(kvp => new XElement("Capture", new XAttribute("Name", kvp.Key), new XAttribute("Span", kvp.Value), GetTextAttribute(text, kvp.Value))))); return element.ToString(); } private static XElement CreateDiagnosticsElement(SourceText text, RegexTree tree) => new XElement("Diagnostics", tree.Diagnostics.Select(d => new XElement("Diagnostic", new XAttribute("Message", d.Message), new XAttribute("Span", d.Span), GetTextAttribute(text, d.Span)))); private static XAttribute GetTextAttribute(SourceText text, TextSpan span) => new XAttribute("Text", text.ToString(span)); private XElement NodeToElement(RegexNode node) { var element = new XElement(node.Kind.ToString()); foreach (var child in node) { element.Add(child.IsNode ? NodeToElement(child.Node) : TokenToElement(child.Token)); } return element; } private static XElement TokenToElement(RegexToken token) { var element = new XElement(token.Kind.ToString()); if (token.Value != null) { element.Add(new XAttribute("value", token.Value)); } if (token.LeadingTrivia.Length > 0) { element.Add(new XElement("Trivia", token.LeadingTrivia.Select(t => TriviaToElement(t)))); } if (token.VirtualChars.Length > 0) { element.Add(token.VirtualChars.CreateString()); } return element; } private static XElement TriviaToElement(RegexTrivia trivia) => new XElement( trivia.Kind.ToString(), trivia.VirtualChars.CreateString()); private void CheckInvariants(RegexTree tree, VirtualCharSequence allChars) { var root = tree.Root; var position = 0; CheckInvariants(root, ref position, allChars); Assert.Equal(allChars.Length, position); } private void CheckInvariants(RegexNode node, ref int position, VirtualCharSequence allChars) { foreach (var child in node) { if (child.IsNode) { CheckInvariants(child.Node, ref position, allChars); } else { CheckInvariants(child.Token, ref position, allChars); } } } private static void CheckInvariants(RegexToken token, ref int position, VirtualCharSequence allChars) { CheckInvariants(token.LeadingTrivia, ref position, allChars); CheckCharacters(token.VirtualChars, ref position, allChars); } private static void CheckInvariants(ImmutableArray<RegexTrivia> leadingTrivia, ref int position, VirtualCharSequence allChars) { foreach (var trivia in leadingTrivia) { CheckInvariants(trivia, ref position, allChars); } } private static void CheckInvariants(RegexTrivia trivia, ref int position, VirtualCharSequence allChars) { switch (trivia.Kind) { case RegexKind.CommentTrivia: case RegexKind.WhitespaceTrivia: break; default: Assert.False(true, "Incorrect trivia kind"); return; } CheckCharacters(trivia.VirtualChars, ref position, allChars); } private static void CheckCharacters(VirtualCharSequence virtualChars, ref int position, VirtualCharSequence allChars) { for (var i = 0; i < virtualChars.Length; i++) { Assert.Equal(allChars[position + i], virtualChars[i]); } position += virtualChars.Length; } [Fact] public void TestDeepRecursion() { var (token, tree, chars) = JustParseTree( @"@""(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((""", RegexOptions.None, conversionFailureOk: false); Assert.False(token.IsMissing); Assert.False(chars.IsDefaultOrEmpty); Assert.Null(tree); } } }
// 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.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.EmbeddedLanguages.Common; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions { using RegexToken = EmbeddedSyntaxToken<RegexKind>; using RegexTrivia = EmbeddedSyntaxTrivia<RegexKind>; public partial class CSharpRegexParserTests { private readonly IVirtualCharService _service = CSharpVirtualCharService.Instance; private const string _statmentPrefix = "var v = "; private static SyntaxToken GetStringToken(string text) { var statement = _statmentPrefix + text; var parsedStatement = SyntaxFactory.ParseStatement(statement); var token = parsedStatement.DescendantTokens().ToArray()[3]; Assert.True(token.Kind() == SyntaxKind.StringLiteralToken); return token; } private void Test(string stringText, string expected, RegexOptions options, bool runSubTreeTests = true, bool allowIndexOutOfRange = false, bool allowNullReference = false, bool allowOutOfMemory = false, bool allowDiagnosticsMismatch = false) { var (tree, sourceText) = TryParseTree(stringText, options, conversionFailureOk: false, allowIndexOutOfRange, allowNullReference, allowOutOfMemory, allowDiagnosticsMismatch); // Tests are allowed to not run the subtree tests. This is because some // subtrees can cause the native regex parser to exhibit very bad behavior // (like not ever actually finishing compiling). if (runSubTreeTests) { TryParseSubTrees(stringText, options, allowIndexOutOfRange, allowNullReference, allowOutOfMemory, allowDiagnosticsMismatch); } const string DoubleQuoteEscaping = "\"\""; var actual = TreeToText(sourceText, tree) .Replace("\"", DoubleQuoteEscaping) .Replace("&quot;", DoubleQuoteEscaping); Assert.Equal(expected.Replace("\"", DoubleQuoteEscaping), actual); } private void TryParseSubTrees( string stringText, RegexOptions options, bool allowIndexOutOfRange, bool allowNullReference, bool allowOutOfMemory, bool allowDiagnosticsMismatch) { // Trim the input from the right and make sure tree invariants hold var current = stringText; while (current != "@\"\"" && current != "\"\"") { current = current.Substring(0, current.Length - 2) + "\""; TryParseTree(current, options, conversionFailureOk: true, allowIndexOutOfRange, allowNullReference, allowOutOfMemory, allowDiagnosticsMismatch); } // Trim the input from the left and make sure tree invariants hold current = stringText; while (current != "@\"\"" && current != "\"\"") { if (current[0] == '@') { current = "@\"" + current.Substring(3); } else { current = "\"" + current.Substring(2); } TryParseTree(current, options, conversionFailureOk: true, allowIndexOutOfRange, allowNullReference, allowOutOfMemory, allowDiagnosticsMismatch); } for (var start = stringText[0] == '@' ? 2 : 1; start < stringText.Length - 1; start++) { TryParseTree( stringText.Substring(0, start) + stringText.Substring(start + 1, stringText.Length - (start + 1)), options, conversionFailureOk: true, allowIndexOutOfRange, allowNullReference, allowOutOfMemory, allowDiagnosticsMismatch); } } private (SyntaxToken, RegexTree, VirtualCharSequence) JustParseTree( string stringText, RegexOptions options, bool conversionFailureOk) { var token = GetStringToken(stringText); var allChars = _service.TryConvertToVirtualChars(token); if (allChars.IsDefault) { Assert.True(conversionFailureOk, "Failed to convert text to token."); return (token, null, allChars); } var tree = RegexParser.TryParse(allChars, options); return (token, tree, allChars); } private (RegexTree, SourceText) TryParseTree( string stringText, RegexOptions options, bool conversionFailureOk, bool allowIndexOutOfRange, bool allowNullReference, bool allowOutOfMemeory, bool allowDiagnosticsMismatch = false) { var (token, tree, allChars) = JustParseTree(stringText, options, conversionFailureOk); if (tree == null) { Assert.True(allChars.IsDefault); return default; } CheckInvariants(tree, allChars); var sourceText = token.SyntaxTree.GetText(); var treeAndText = (tree, sourceText); Regex regex = null; try { regex = new Regex(token.ValueText, options); } catch (IndexOutOfRangeException) when (allowIndexOutOfRange) { // bug with .NET regex parser. Can happen with patterns like: (?<-0 Assert.NotEmpty(tree.Diagnostics); return treeAndText; } catch (NullReferenceException) when (allowNullReference) { // bug with .NET regex parser. can happen with patterns like: (?(?S)) return treeAndText; } catch (OutOfMemoryException) when (allowOutOfMemeory) { // bug with .NET regex parser. can happen with patterns like: a{2147483647,} return treeAndText; } catch (ArgumentException ex) { if (!allowDiagnosticsMismatch) { Assert.NotEmpty(tree.Diagnostics); // Ensure the diagnostic we emit is the same as the .NET one. Note: we can only // do this in en-US as that's the only culture where we control the text exactly // and can ensure it exactly matches Regex. We depend on localization to do a // good enough job here for other languages. if (Thread.CurrentThread.CurrentCulture.Name == "en-US") { Assert.True(tree.Diagnostics.Any(d => ex.Message.Contains(d.Message))); } } return treeAndText; } if (!tree.Diagnostics.IsEmpty && !allowDiagnosticsMismatch) { var expectedDiagnostics = CreateDiagnosticsElement(sourceText, tree); Assert.False(true, "Expected diagnostics: \r\n" + expectedDiagnostics.ToString().Replace(@"""", @"""""")); } Assert.True(regex.GetGroupNumbers().OrderBy(v => v).SequenceEqual( tree.CaptureNumbersToSpan.Keys.OrderBy(v => v).Select(v => (int)v))); Assert.True(regex.GetGroupNames().Where(v => !int.TryParse(v, out _)).OrderBy(v => v).SequenceEqual( tree.CaptureNamesToSpan.Keys.OrderBy(v => v))); return treeAndText; } private string TreeToText(SourceText text, RegexTree tree) { var element = new XElement("Tree", NodeToElement(tree.Root)); if (tree.Diagnostics.Length > 0) { element.Add(CreateDiagnosticsElement(text, tree)); } element.Add(new XElement("Captures", tree.CaptureNumbersToSpan.OrderBy(kvp => kvp.Key).Select(kvp => new XElement("Capture", new XAttribute("Name", kvp.Key), new XAttribute("Span", kvp.Value), GetTextAttribute(text, kvp.Value))), tree.CaptureNamesToSpan.OrderBy(kvp => kvp.Key).Select(kvp => new XElement("Capture", new XAttribute("Name", kvp.Key), new XAttribute("Span", kvp.Value), GetTextAttribute(text, kvp.Value))))); return element.ToString(); } private static XElement CreateDiagnosticsElement(SourceText text, RegexTree tree) => new XElement("Diagnostics", tree.Diagnostics.Select(d => new XElement("Diagnostic", new XAttribute("Message", d.Message), new XAttribute("Span", d.Span), GetTextAttribute(text, d.Span)))); private static XAttribute GetTextAttribute(SourceText text, TextSpan span) => new XAttribute("Text", text.ToString(span)); private XElement NodeToElement(RegexNode node) { var element = new XElement(node.Kind.ToString()); foreach (var child in node) { element.Add(child.IsNode ? NodeToElement(child.Node) : TokenToElement(child.Token)); } return element; } private static XElement TokenToElement(RegexToken token) { var element = new XElement(token.Kind.ToString()); if (token.Value != null) { element.Add(new XAttribute("value", token.Value)); } if (token.LeadingTrivia.Length > 0) { element.Add(new XElement("Trivia", token.LeadingTrivia.Select(t => TriviaToElement(t)))); } if (token.VirtualChars.Length > 0) { element.Add(token.VirtualChars.CreateString()); } return element; } private static XElement TriviaToElement(RegexTrivia trivia) => new XElement( trivia.Kind.ToString(), trivia.VirtualChars.CreateString()); private void CheckInvariants(RegexTree tree, VirtualCharSequence allChars) { var root = tree.Root; var position = 0; CheckInvariants(root, ref position, allChars); Assert.Equal(allChars.Length, position); } private void CheckInvariants(RegexNode node, ref int position, VirtualCharSequence allChars) { foreach (var child in node) { if (child.IsNode) { CheckInvariants(child.Node, ref position, allChars); } else { CheckInvariants(child.Token, ref position, allChars); } } } private static void CheckInvariants(RegexToken token, ref int position, VirtualCharSequence allChars) { CheckInvariants(token.LeadingTrivia, ref position, allChars); CheckCharacters(token.VirtualChars, ref position, allChars); } private static void CheckInvariants(ImmutableArray<RegexTrivia> leadingTrivia, ref int position, VirtualCharSequence allChars) { foreach (var trivia in leadingTrivia) { CheckInvariants(trivia, ref position, allChars); } } private static void CheckInvariants(RegexTrivia trivia, ref int position, VirtualCharSequence allChars) { switch (trivia.Kind) { case RegexKind.CommentTrivia: case RegexKind.WhitespaceTrivia: break; default: Assert.False(true, "Incorrect trivia kind"); return; } CheckCharacters(trivia.VirtualChars, ref position, allChars); } private static void CheckCharacters(VirtualCharSequence virtualChars, ref int position, VirtualCharSequence allChars) { for (var i = 0; i < virtualChars.Length; i++) { Assert.Equal(allChars[position + i], virtualChars[i]); } position += virtualChars.Length; } [Fact] public void TestDeepRecursion() { var (token, tree, chars) = JustParseTree( @"@""(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((""", RegexOptions.None, conversionFailureOk: false); Assert.False(token.IsMissing); Assert.False(chars.IsDefaultOrEmpty); Assert.Null(tree); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxEquivalenceTests.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. Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxEquivalenceTests Private Function NewLines(p1 As String) As String Return p1.Replace("\n", vbCrLf) End Function Private Sub VerifyEquivalent(tree1 As SyntaxTree, tree2 As SyntaxTree, topLevel As Boolean) Assert.True(SyntaxFactory.AreEquivalent(tree1, tree2, topLevel)) ' now try as if the second tree were created from scratch. Dim tree3 = VisualBasicSyntaxTree.ParseText(tree2.GetText().ToString()) Assert.True(SyntaxFactory.AreEquivalent(tree1, tree3, topLevel)) End Sub Private Sub VerifyNotEquivalent(tree1 As SyntaxTree, tree2 As SyntaxTree, topLevel As Boolean) Assert.False(SyntaxFactory.AreEquivalent(tree1, tree2, topLevel)) ' now try as if the second tree were created from scratch. Dim tree3 = VisualBasicSyntaxTree.ParseText(tree2.GetText().ToString()) Assert.False(SyntaxFactory.AreEquivalent(tree1, tree3, topLevel)) End Sub <Fact> Public Sub TestEmptyTrees() Dim text = "" Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddingComment() Dim text = "" Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = tree1.WithInsertAt(0, "' goo") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddingActivePPDirective() Dim text = "" Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = tree1.WithInsertAt(0, NewLines("#if true \n\n#end if")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddingInactivePPDirective() Dim text = "" Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = tree1.WithInsertAt(0, NewLines("#if false \n\n#end if")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingEmpty() Dim text = "" Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = tree1.WithInsertAt(0, NewLines("namespace N \n end namespace")) VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddingClass() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n end namespace")) Dim tree2 = tree1.WithInsertBefore("end", NewLines("class C \n end class \n")) VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestRenameOuter() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("N", "N1") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestRenameInner() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n dim z = 0 \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("z", "y") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestRenameOuterToSamename() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("N", "N") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestRenameInnerToSameName() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n dim z = 0 \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("z", "z") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddingMethod() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n end class \n end namespace")) Dim tree2 = tree1.WithInsertBefore("end", NewLines("sub Goo() \n end sub \n")) VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddingLocal() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithInsertBefore("end", NewLines("dim i as Integer \n ")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestRemovingLocal() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n dim z = 0 \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithRemoveFirst("dim z = 0") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingConstLocal() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n const i = 5 \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingEnumMember() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("enum E \n i = 5 \n end enum")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingAttribute() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n <Obsolete(true)>\nclass C \n const i = 5 \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("true", "false") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingMethodCall() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n Console.Write(0) \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("Write", "WriteLine") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingUsing() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("Imports System \n namespace N \n class C \n sub Goo() \n Console.Write(0) \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("System", "System.Linq") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingBaseType() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n Console.Write(0) \n end sub \n end class")) Dim tree2 = tree1.WithInsertBefore("sub", "Inherits B \n") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingMethodType() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n Console.Write(0) \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst("sub Goo()", "function Goo() as Integer") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddComment() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n Console.Write(0) \n end sub \n end class")) Dim tree2 = tree1.WithInsertBefore("class", NewLines("' Comment\n")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestCommentOutCode() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n Console.Write(0) \n end sub \n end class")) Dim tree2 = tree1.WithInsertBefore("class", "' ") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddDocComment() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n Console.Write(0) \n end sub \n end class")) Dim tree2 = tree1.WithInsertBefore("class", NewLines("''' Comment \n")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestSurroundMethodWithActivePPRegion() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst(NewLines("sub Goo() \n end sub \n"), NewLines("\n #if true \n sub Goo() \n end sub \n #end if \n")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestSurroundMethodWithInactivePPRegion() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst(NewLines("sub Goo() \n end sub \n"), NewLines("\n #if false \n sub Goo() \n end sub \n #end if \n")) VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestSurroundStatementWithActivePPRegion() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n dim i as Integer \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst(NewLines("dim i as Integer \n"), NewLines("\n #if true \n dim i as Integer \n #end if \n")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestSurroundStatementWithInactivePPRegion() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n dim i as Integer \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst(NewLines("dim i as Integer \n"), NewLines("\n #if false \n dim i as Integer \n #end if \n")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangeWhitespace() Dim text = NewLines("class C \n sub Goo() \n dim i as Integer \n end sub \n end class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace(" ", " ")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestSkippedText() Dim text = NewLines("Imports System \n Modle Program \n Sub Main(args As String()) \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Modle ", "Mode ")) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestUpdateInterpolatedString() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n Console.Write($""Hello{123:N1}"") \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("N1", "N2") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) tree2 = tree1.WithReplaceFirst("Hello", "World") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub #Region "Field" <Fact> Public Sub TestRemovingField1() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n dim i = 5 \n dim j = 6 \n end class \n end namespace")) Dim tree2 = tree1.WithRemoveFirst("dim i = 5") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestRemovingField2() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n dim i = 5 \n dim j = 6 \n end class \n end namespace")) Dim tree2 = tree1.WithRemoveFirst("dim j = 6") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingFieldInitializer() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n dim i = 5 \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingFieldAsNewInitializer1() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n dim i As New C(5) \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingFieldAsNewInitializer2() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n dim i, j As New C(5) \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingField2() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n dim i = 5, j = 7 \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("7", "8") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) tree2 = tree1.WithReplaceFirst("5", "6") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingConstField() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n const i = 5 \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingConstField2() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n const i = 5, j = 7 \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) tree2 = tree1.WithReplaceFirst("7", "8") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub #End Region #Region "Methods" <Fact> Public Sub TestMethod_Body() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) \n Body(1) \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Body(1)", "Body(2)")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_Modifiers() Dim text = NewLines("Imports System \n Module Program \n Friend Sub Main(args As String()) \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Friend", "")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ParameterName() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("args", "arg")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ParameterAttribute() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("args", "<A>args")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ParameterModifier() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("args", "ByRef args")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ParameterDefaultValue() Dim text = NewLines("Imports System \n Module Program \n Sub Main(Optional arg As Integer = 123) \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("123", "456")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_Kind() Dim text = NewLines("Imports System \n Module Program \n Function Main(Optional arg As Integer = 123) \n \n End Function \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Function", "Sub")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ReturnType1() Dim text = NewLines("Imports System \n Module Program \n Function Main(Optional arg As Integer = 123) As Integer \n \n End Function \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("As Integer", "")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ReturnType2() Dim text = NewLines("Imports System \n Module Program \n Function Main(Optional arg As Integer = 123) As C \n \n End Function \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("As C", "As D")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ReturnTypeCustomAttribute() Dim text = NewLines("Imports System \n Module Program \n Function Main(Optional arg As Integer = 123) As <A(1)>C \n \n End Function \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("As <A(1)>C", "As <A(2)>C")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_Handles() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) Handles E.Goo \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("E.Goo", "E.Bar")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_Implements() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) Implements I.Goo \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("I.Goo", "I.Bar")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_RemoveEnd() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) Implements I.Goo \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("End Sub", "")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ChangeEndKind() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) Implements I.Goo \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("End Sub", "End Function")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_CommentOutMethodCode() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n Console.Write(0) \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst("Console.Write(0)", "' Console.Write(0) ") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestMethod_CommentOutMethod() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst(NewLines("sub Goo() \n end sub \n"), NewLines("' sub Goo() \n ' end sub \n")) VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub #End Region #Region "Constructor" <Fact> Public Sub TestConstructor_Body() Dim text = NewLines("Imports System \n Class Program \n Sub New(args As String()) \n Body(1) \n End Sub \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Body(1)", "Body(2)")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestConstructor_Initializer() Dim text = NewLines("Imports System \n Class Program \n Sub New(args As String()) \n MyBase.New(1) \n End Sub \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("MyBase", "Me")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestConstructor_ParameterDefaultValue() Dim text = NewLines("Imports System \n Class Program \n Sub New(Optional arg As Integer = 123) \n \n End Sub \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("123", "456")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub #End Region #Region "Operator" <Fact> Public Sub TestOperator_Body() Dim text = NewLines("Imports System \n Class C \n Shared Operator *(a As C, b As C) As Integer \n Return 0 \n End Operator \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Return 0", "Return 1")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestOperator_ParameterName() Dim text = NewLines("Imports System \n Class C \n Shared Operator *(a As C, b As C) As Integer \n Return 0 \n End Operator \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("b As C", "c As C")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub #End Region #Region "Property" <Fact> Public Sub TestPropertyAccessor_Attribute1() Dim text = NewLines("Imports System \n Class Program \n Property P As Integer \n <A(1)>Get \n End Get \n Set(value As Integer) \n End Set \n End Property \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestPropertyAccessor_Attribute2() Dim text = NewLines("Imports System \n Class Program \n Property P As Integer \n Get \n End Get \n <A(1)>Set(value As Integer) \n End Set \n End Property \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestPropertyAccessor_Attribute3() Dim text = NewLines("Imports System \n Class Program \n Property P As Integer \n Get \n End Get \n Set(<A(1)>value As Integer) \n End Set \n End Property \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestProperty_Parameters() Dim text = NewLines("Imports System \n Class Program \n Property P(a As Integer = 123) \n Get \n End Get \n Set(value As Integer) \n End Set \n End Property \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("123", "345")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestAutoProperty_Initializer1() Dim text = NewLines("Imports System \n Class Program \n Property P As Integer = 123 \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("123", "345")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestAutoProperty_Initializer_InvalidSyntax() Dim text = NewLines("Imports System \n Class Program \n Property P(a As Integer = 123) As Integer = 1 \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("123", "345")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub #End Region #Region "Event" <Fact> Public Sub TestEventAccessor_Attribute1() Dim text = NewLines("Imports System \n Class Program \n Custom Event E As Action \n <A(1)>AddHandler(value As Action) \n End AddHandler \n RemoveHandler(value As Action) \n End RemoveHandler \n RaiseEvent() \n End RaiseEvent \n End Event \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestEventAccessor_Attribute2() Dim text = NewLines("Imports System \n Class Program \n Custom Event E As Action \n AddHandler(value As Action) \n End AddHandler \n <A(1)>RemoveHandler(value As Action) \n End RemoveHandler \n RaiseEvent() \n End RaiseEvent \n End Event \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestEventAccessor_Attribute3() Dim text = NewLines("Imports System \n Class Program \n Custom Event E As Action \n AddHandler(value As Action) \n End AddHandler \n RemoveHandler(value As Action) \n End RemoveHandler \n <A(1)>RaiseEvent() \n End RaiseEvent \n End Event \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestEventAccessor_Attribute4() Dim text = NewLines("Imports System \n Class Program \n Custom Event E As Action \n AddHandler(<A(1)>value As Action) \n End AddHandler \n RemoveHandler(value As Action) \n End RemoveHandler \n RaiseEvent() \n End RaiseEvent \n End Event \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestEventAccessor_Attribute5() Dim text = NewLines("Imports System \n Class Program \n Custom Event E As Action \n AddHandler(value As Action) \n End AddHandler \n RemoveHandler(<A(1)>value As Action) \n End RemoveHandler \n RaiseEvent() \n End RaiseEvent \n End Event \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub #End Region #Region "Declare" <Fact> Public Sub TestDeclare_Modifier() Dim text = NewLines("Imports System \n Module Program \n Declare Ansi Function Goo Lib ""goo"" Alias ""bar"" () As Integer \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Ansi", "Unicode")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestDeclare_LibName() Dim text = NewLines("Imports System \n Module Program \n Declare Ansi Function Goo Lib ""goo"" Alias ""bar"" () As Integer \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("goo", "goo2")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestDeclare_AliasName() Dim text = NewLines("Imports System \n Module Program \n Declare Ansi Function Goo Lib ""goo"" Alias ""bar"" () As Integer \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("bar", "bar2")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestDeclare_ReturnType() Dim text = NewLines("Imports System \n Module Program \n Declare Ansi Function Goo Lib ""goo"" Alias ""bar"" () As Integer \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Integer", "Boolean")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestDeclare_Parameter() Dim text = NewLines("Imports System \n Module Program \n Declare Ansi Function Goo Lib ""goo"" Alias ""bar"" () As Integer \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("()", "(a As Integer)")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub #End Region 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. Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxEquivalenceTests Private Function NewLines(p1 As String) As String Return p1.Replace("\n", vbCrLf) End Function Private Sub VerifyEquivalent(tree1 As SyntaxTree, tree2 As SyntaxTree, topLevel As Boolean) Assert.True(SyntaxFactory.AreEquivalent(tree1, tree2, topLevel)) ' now try as if the second tree were created from scratch. Dim tree3 = VisualBasicSyntaxTree.ParseText(tree2.GetText().ToString()) Assert.True(SyntaxFactory.AreEquivalent(tree1, tree3, topLevel)) End Sub Private Sub VerifyNotEquivalent(tree1 As SyntaxTree, tree2 As SyntaxTree, topLevel As Boolean) Assert.False(SyntaxFactory.AreEquivalent(tree1, tree2, topLevel)) ' now try as if the second tree were created from scratch. Dim tree3 = VisualBasicSyntaxTree.ParseText(tree2.GetText().ToString()) Assert.False(SyntaxFactory.AreEquivalent(tree1, tree3, topLevel)) End Sub <Fact> Public Sub TestEmptyTrees() Dim text = "" Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddingComment() Dim text = "" Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = tree1.WithInsertAt(0, "' goo") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddingActivePPDirective() Dim text = "" Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = tree1.WithInsertAt(0, NewLines("#if true \n\n#end if")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddingInactivePPDirective() Dim text = "" Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = tree1.WithInsertAt(0, NewLines("#if false \n\n#end if")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingEmpty() Dim text = "" Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = tree1.WithInsertAt(0, NewLines("namespace N \n end namespace")) VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddingClass() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n end namespace")) Dim tree2 = tree1.WithInsertBefore("end", NewLines("class C \n end class \n")) VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestRenameOuter() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("N", "N1") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestRenameInner() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n dim z = 0 \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("z", "y") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestRenameOuterToSamename() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("N", "N") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestRenameInnerToSameName() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n dim z = 0 \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("z", "z") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddingMethod() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n end class \n end namespace")) Dim tree2 = tree1.WithInsertBefore("end", NewLines("sub Goo() \n end sub \n")) VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddingLocal() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithInsertBefore("end", NewLines("dim i as Integer \n ")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestRemovingLocal() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n dim z = 0 \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithRemoveFirst("dim z = 0") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingConstLocal() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n const i = 5 \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingEnumMember() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("enum E \n i = 5 \n end enum")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingAttribute() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n <Obsolete(true)>\nclass C \n const i = 5 \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("true", "false") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingMethodCall() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n Console.Write(0) \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("Write", "WriteLine") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingUsing() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("Imports System \n namespace N \n class C \n sub Goo() \n Console.Write(0) \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("System", "System.Linq") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingBaseType() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n Console.Write(0) \n end sub \n end class")) Dim tree2 = tree1.WithInsertBefore("sub", "Inherits B \n") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingMethodType() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n Console.Write(0) \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst("sub Goo()", "function Goo() as Integer") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddComment() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n Console.Write(0) \n end sub \n end class")) Dim tree2 = tree1.WithInsertBefore("class", NewLines("' Comment\n")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestCommentOutCode() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n Console.Write(0) \n end sub \n end class")) Dim tree2 = tree1.WithInsertBefore("class", "' ") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestAddDocComment() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n Console.Write(0) \n end sub \n end class")) Dim tree2 = tree1.WithInsertBefore("class", NewLines("''' Comment \n")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestSurroundMethodWithActivePPRegion() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst(NewLines("sub Goo() \n end sub \n"), NewLines("\n #if true \n sub Goo() \n end sub \n #end if \n")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestSurroundMethodWithInactivePPRegion() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst(NewLines("sub Goo() \n end sub \n"), NewLines("\n #if false \n sub Goo() \n end sub \n #end if \n")) VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestSurroundStatementWithActivePPRegion() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n dim i as Integer \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst(NewLines("dim i as Integer \n"), NewLines("\n #if true \n dim i as Integer \n #end if \n")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestSurroundStatementWithInactivePPRegion() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n dim i as Integer \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst(NewLines("dim i as Integer \n"), NewLines("\n #if false \n dim i as Integer \n #end if \n")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangeWhitespace() Dim text = NewLines("class C \n sub Goo() \n dim i as Integer \n end sub \n end class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace(" ", " ")) VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestSkippedText() Dim text = NewLines("Imports System \n Modle Program \n Sub Main(args As String()) \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Modle ", "Mode ")) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestUpdateInterpolatedString() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n sub Goo() \n Console.Write($""Hello{123:N1}"") \n end sub \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("N1", "N2") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) tree2 = tree1.WithReplaceFirst("Hello", "World") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub #Region "Field" <Fact> Public Sub TestRemovingField1() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n dim i = 5 \n dim j = 6 \n end class \n end namespace")) Dim tree2 = tree1.WithRemoveFirst("dim i = 5") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestRemovingField2() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n dim i = 5 \n dim j = 6 \n end class \n end namespace")) Dim tree2 = tree1.WithRemoveFirst("dim j = 6") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingFieldInitializer() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n dim i = 5 \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingFieldAsNewInitializer1() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n dim i As New C(5) \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingFieldAsNewInitializer2() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n dim i, j As New C(5) \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingField2() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n dim i = 5, j = 7 \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("7", "8") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) tree2 = tree1.WithReplaceFirst("5", "6") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingConstField() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n const i = 5 \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestChangingConstField2() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("namespace N \n class C \n const i = 5, j = 7 \n end class \n end namespace")) Dim tree2 = tree1.WithReplaceFirst("5", "6") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) tree2 = tree1.WithReplaceFirst("7", "8") VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub #End Region #Region "Methods" <Fact> Public Sub TestMethod_Body() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) \n Body(1) \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Body(1)", "Body(2)")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_Modifiers() Dim text = NewLines("Imports System \n Module Program \n Friend Sub Main(args As String()) \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Friend", "")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ParameterName() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("args", "arg")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ParameterAttribute() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("args", "<A>args")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ParameterModifier() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("args", "ByRef args")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ParameterDefaultValue() Dim text = NewLines("Imports System \n Module Program \n Sub Main(Optional arg As Integer = 123) \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("123", "456")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_Kind() Dim text = NewLines("Imports System \n Module Program \n Function Main(Optional arg As Integer = 123) \n \n End Function \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Function", "Sub")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ReturnType1() Dim text = NewLines("Imports System \n Module Program \n Function Main(Optional arg As Integer = 123) As Integer \n \n End Function \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("As Integer", "")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ReturnType2() Dim text = NewLines("Imports System \n Module Program \n Function Main(Optional arg As Integer = 123) As C \n \n End Function \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("As C", "As D")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ReturnTypeCustomAttribute() Dim text = NewLines("Imports System \n Module Program \n Function Main(Optional arg As Integer = 123) As <A(1)>C \n \n End Function \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("As <A(1)>C", "As <A(2)>C")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_Handles() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) Handles E.Goo \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("E.Goo", "E.Bar")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_Implements() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) Implements I.Goo \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("I.Goo", "I.Bar")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_RemoveEnd() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) Implements I.Goo \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("End Sub", "")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_ChangeEndKind() Dim text = NewLines("Imports System \n Module Program \n Sub Main(args As String()) Implements I.Goo \n \n End Sub \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("End Sub", "End Function")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestMethod_CommentOutMethodCode() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n Console.Write(0) \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst("Console.Write(0)", "' Console.Write(0) ") VerifyEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub <Fact> Public Sub TestMethod_CommentOutMethod() Dim tree1 = VisualBasicSyntaxTree.ParseText(NewLines("class C \n sub Goo() \n end sub \n end class")) Dim tree2 = tree1.WithReplaceFirst(NewLines("sub Goo() \n end sub \n"), NewLines("' sub Goo() \n ' end sub \n")) VerifyNotEquivalent(tree1, tree2, topLevel:=True) VerifyNotEquivalent(tree1, tree2, topLevel:=False) End Sub #End Region #Region "Constructor" <Fact> Public Sub TestConstructor_Body() Dim text = NewLines("Imports System \n Class Program \n Sub New(args As String()) \n Body(1) \n End Sub \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Body(1)", "Body(2)")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestConstructor_Initializer() Dim text = NewLines("Imports System \n Class Program \n Sub New(args As String()) \n MyBase.New(1) \n End Sub \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("MyBase", "Me")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestConstructor_ParameterDefaultValue() Dim text = NewLines("Imports System \n Class Program \n Sub New(Optional arg As Integer = 123) \n \n End Sub \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("123", "456")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub #End Region #Region "Operator" <Fact> Public Sub TestOperator_Body() Dim text = NewLines("Imports System \n Class C \n Shared Operator *(a As C, b As C) As Integer \n Return 0 \n End Operator \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Return 0", "Return 1")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestOperator_ParameterName() Dim text = NewLines("Imports System \n Class C \n Shared Operator *(a As C, b As C) As Integer \n Return 0 \n End Operator \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("b As C", "c As C")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub #End Region #Region "Property" <Fact> Public Sub TestPropertyAccessor_Attribute1() Dim text = NewLines("Imports System \n Class Program \n Property P As Integer \n <A(1)>Get \n End Get \n Set(value As Integer) \n End Set \n End Property \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestPropertyAccessor_Attribute2() Dim text = NewLines("Imports System \n Class Program \n Property P As Integer \n Get \n End Get \n <A(1)>Set(value As Integer) \n End Set \n End Property \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestPropertyAccessor_Attribute3() Dim text = NewLines("Imports System \n Class Program \n Property P As Integer \n Get \n End Get \n Set(<A(1)>value As Integer) \n End Set \n End Property \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestProperty_Parameters() Dim text = NewLines("Imports System \n Class Program \n Property P(a As Integer = 123) \n Get \n End Get \n Set(value As Integer) \n End Set \n End Property \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("123", "345")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestAutoProperty_Initializer1() Dim text = NewLines("Imports System \n Class Program \n Property P As Integer = 123 \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("123", "345")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestAutoProperty_Initializer_InvalidSyntax() Dim text = NewLines("Imports System \n Class Program \n Property P(a As Integer = 123) As Integer = 1 \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("123", "345")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub #End Region #Region "Event" <Fact> Public Sub TestEventAccessor_Attribute1() Dim text = NewLines("Imports System \n Class Program \n Custom Event E As Action \n <A(1)>AddHandler(value As Action) \n End AddHandler \n RemoveHandler(value As Action) \n End RemoveHandler \n RaiseEvent() \n End RaiseEvent \n End Event \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestEventAccessor_Attribute2() Dim text = NewLines("Imports System \n Class Program \n Custom Event E As Action \n AddHandler(value As Action) \n End AddHandler \n <A(1)>RemoveHandler(value As Action) \n End RemoveHandler \n RaiseEvent() \n End RaiseEvent \n End Event \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestEventAccessor_Attribute3() Dim text = NewLines("Imports System \n Class Program \n Custom Event E As Action \n AddHandler(value As Action) \n End AddHandler \n RemoveHandler(value As Action) \n End RemoveHandler \n <A(1)>RaiseEvent() \n End RaiseEvent \n End Event \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestEventAccessor_Attribute4() Dim text = NewLines("Imports System \n Class Program \n Custom Event E As Action \n AddHandler(<A(1)>value As Action) \n End AddHandler \n RemoveHandler(value As Action) \n End RemoveHandler \n RaiseEvent() \n End RaiseEvent \n End Event \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestEventAccessor_Attribute5() Dim text = NewLines("Imports System \n Class Program \n Custom Event E As Action \n AddHandler(value As Action) \n End AddHandler \n RemoveHandler(<A(1)>value As Action) \n End RemoveHandler \n RaiseEvent() \n End RaiseEvent \n End Event \n End Class") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("<A(1)>", "<A(2)>")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub #End Region #Region "Declare" <Fact> Public Sub TestDeclare_Modifier() Dim text = NewLines("Imports System \n Module Program \n Declare Ansi Function Goo Lib ""goo"" Alias ""bar"" () As Integer \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Ansi", "Unicode")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestDeclare_LibName() Dim text = NewLines("Imports System \n Module Program \n Declare Ansi Function Goo Lib ""goo"" Alias ""bar"" () As Integer \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("goo", "goo2")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestDeclare_AliasName() Dim text = NewLines("Imports System \n Module Program \n Declare Ansi Function Goo Lib ""goo"" Alias ""bar"" () As Integer \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("bar", "bar2")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestDeclare_ReturnType() Dim text = NewLines("Imports System \n Module Program \n Declare Ansi Function Goo Lib ""goo"" Alias ""bar"" () As Integer \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("Integer", "Boolean")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub <Fact> Public Sub TestDeclare_Parameter() Dim text = NewLines("Imports System \n Module Program \n Declare Ansi Function Goo Lib ""goo"" Alias ""bar"" () As Integer \n End Module") Dim tree1 = VisualBasicSyntaxTree.ParseText(text) Dim tree2 = VisualBasicSyntaxTree.ParseText(text.Replace("()", "(a As Integer)")) VerifyNotEquivalent(tree1, tree2, topLevel:=False) VerifyNotEquivalent(tree1, tree2, topLevel:=True) End Sub #End Region End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/Core/Portable/Completion/CommonCompletionUtilities.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion { internal static class CommonCompletionUtilities { private const string NonBreakingSpaceString = "\x00A0"; public static TextSpan GetWordSpan(SourceText text, int position, Func<char, bool> isWordStartCharacter, Func<char, bool> isWordCharacter) { return GetWordSpan(text, position, isWordStartCharacter, isWordCharacter, alwaysExtendEndSpan: false); } public static TextSpan GetWordSpan(SourceText text, int position, Func<char, bool> isWordStartCharacter, Func<char, bool> isWordCharacter, bool alwaysExtendEndSpan = false) { var start = position; while (start > 0 && isWordStartCharacter(text[start - 1])) { start--; } // If we're brought up in the middle of a word, extend to the end of the word as well. // This means that if a user brings up the completion list at the start of the word they // will "insert" the text before what's already there (useful for qualifying existing // text). However, if they bring up completion in the "middle" of a word, then they will // "overwrite" the text. Useful for correcting misspellings or just replacing unwanted // code with new code. var end = position; if (start != position || alwaysExtendEndSpan) { while (end < text.Length && isWordCharacter(text[end])) { end++; } } return TextSpan.FromBounds(start, end); } public static bool IsStartingNewWord(SourceText text, int characterPosition, Func<char, bool> isWordStartCharacter, Func<char, bool> isWordCharacter) { var ch = text[characterPosition]; if (!isWordStartCharacter(ch)) { return false; } // Only want to trigger if we're the first character in an identifier. If there's a // character before or after us, then we don't want to trigger. if (characterPosition > 0 && isWordCharacter(text[characterPosition - 1])) { return false; } if (characterPosition < text.Length - 1 && isWordCharacter(text[characterPosition + 1])) { return false; } return true; } public static Func<CancellationToken, Task<CompletionDescription>> CreateDescriptionFactory( Workspace workspace, SemanticModel semanticModel, int position, ISymbol symbol) { return CreateDescriptionFactory(workspace, semanticModel, position, new[] { symbol }); } public static Func<CancellationToken, Task<CompletionDescription>> CreateDescriptionFactory( Workspace workspace, SemanticModel semanticModel, int position, IReadOnlyList<ISymbol> symbols) { return c => CreateDescriptionAsync(workspace, semanticModel, position, symbols, supportedPlatforms: null, cancellationToken: c); } public static Func<CancellationToken, Task<CompletionDescription>> CreateDescriptionFactory( Workspace workspace, SemanticModel semanticModel, int position, IReadOnlyList<ISymbol> symbols, SupportedPlatformData supportedPlatforms) { return c => CreateDescriptionAsync(workspace, semanticModel, position, symbols, supportedPlatforms: supportedPlatforms, cancellationToken: c); } public static async Task<CompletionDescription> CreateDescriptionAsync( Workspace workspace, SemanticModel semanticModel, int position, ISymbol symbol, int overloadCount, SupportedPlatformData supportedPlatforms, CancellationToken cancellationToken) { var symbolDisplayService = workspace.Services.GetLanguageServices(semanticModel.Language).GetService<ISymbolDisplayService>(); var formatter = workspace.Services.GetLanguageServices(semanticModel.Language).GetService<IDocumentationCommentFormattingService>(); // TODO(cyrusn): Figure out a way to cancel this. var sections = await symbolDisplayService.ToDescriptionGroupsAsync(workspace, semanticModel, position, ImmutableArray.Create(symbol), cancellationToken).ConfigureAwait(false); if (!sections.ContainsKey(SymbolDescriptionGroups.MainDescription)) { return CompletionDescription.Empty; } var textContentBuilder = new List<TaggedText>(); textContentBuilder.AddRange(sections[SymbolDescriptionGroups.MainDescription]); switch (symbol.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.NamedType: if (overloadCount > 0) { var isGeneric = symbol.GetArity() > 0; textContentBuilder.AddSpace(); textContentBuilder.AddPunctuation("("); textContentBuilder.AddPunctuation("+"); textContentBuilder.AddText(NonBreakingSpaceString + overloadCount.ToString()); AddOverloadPart(textContentBuilder, overloadCount, isGeneric); textContentBuilder.AddPunctuation(")"); } break; } AddDocumentationPart(textContentBuilder, symbol, semanticModel, position, formatter, cancellationToken); if (sections.TryGetValue(SymbolDescriptionGroups.AwaitableUsageText, out var parts)) { textContentBuilder.AddRange(parts); } if (sections.TryGetValue(SymbolDescriptionGroups.AnonymousTypes, out parts)) { if (!parts.IsDefaultOrEmpty) { textContentBuilder.AddLineBreak(); textContentBuilder.AddLineBreak(); textContentBuilder.AddRange(parts); } } if (supportedPlatforms != null) { textContentBuilder.AddLineBreak(); textContentBuilder.AddRange(supportedPlatforms.ToDisplayParts().ToTaggedText()); } return CompletionDescription.Create(textContentBuilder.AsImmutable()); } public static Task<CompletionDescription> CreateDescriptionAsync( Workspace workspace, SemanticModel semanticModel, int position, IReadOnlyList<ISymbol> symbols, SupportedPlatformData supportedPlatforms, CancellationToken cancellationToken) { // Lets try to find the first non-obsolete symbol (overload) and fall-back // to the first symbol if all are obsolete. var symbol = symbols.FirstOrDefault(s => !s.IsObsolete()) ?? symbols[0]; return CreateDescriptionAsync(workspace, semanticModel, position, symbol, overloadCount: symbols.Count - 1, supportedPlatforms, cancellationToken); } private static void AddOverloadPart(List<TaggedText> textContentBuilder, int overloadCount, bool isGeneric) { var text = isGeneric ? overloadCount == 1 ? FeaturesResources.generic_overload : FeaturesResources.generic_overloads : overloadCount == 1 ? FeaturesResources.overload : FeaturesResources.overloads_; textContentBuilder.AddText(NonBreakingSpaceString + text); } private static void AddDocumentationPart( List<TaggedText> textContentBuilder, ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter, CancellationToken cancellationToken) { var documentation = symbol.GetDocumentationParts(semanticModel, position, formatter, cancellationToken); if (documentation.Any()) { textContentBuilder.AddLineBreak(); textContentBuilder.AddRange(documentation); } } internal static bool IsTextualTriggerString(SourceText text, int characterPosition, string value) { // The character position starts at the last character of 'value'. So if 'value' has // length 1, then we don't want to move, if it has length 2 we want to move back one, // etc. characterPosition = characterPosition - value.Length + 1; for (var i = 0; i < value.Length; i++, characterPosition++) { if (characterPosition < 0 || characterPosition >= text.Length) { return false; } if (text[characterPosition] != value[i]) { return false; } } return true; } public static bool TryRemoveAttributeSuffix(ISymbol symbol, SyntaxContext context, out string name) { var isAttributeNameContext = context.IsAttributeNameContext; var syntaxFacts = context.GetLanguageService<ISyntaxFactsService>(); if (!isAttributeNameContext) { name = null; return false; } // Do the symbol textual check first. Then the more expensive symbolic check. if (!symbol.Name.TryGetWithoutAttributeSuffix(syntaxFacts.IsCaseSensitive, out name) || !symbol.IsAttribute()) { return false; } 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion { internal static class CommonCompletionUtilities { private const string NonBreakingSpaceString = "\x00A0"; public static TextSpan GetWordSpan(SourceText text, int position, Func<char, bool> isWordStartCharacter, Func<char, bool> isWordCharacter) { return GetWordSpan(text, position, isWordStartCharacter, isWordCharacter, alwaysExtendEndSpan: false); } public static TextSpan GetWordSpan(SourceText text, int position, Func<char, bool> isWordStartCharacter, Func<char, bool> isWordCharacter, bool alwaysExtendEndSpan = false) { var start = position; while (start > 0 && isWordStartCharacter(text[start - 1])) { start--; } // If we're brought up in the middle of a word, extend to the end of the word as well. // This means that if a user brings up the completion list at the start of the word they // will "insert" the text before what's already there (useful for qualifying existing // text). However, if they bring up completion in the "middle" of a word, then they will // "overwrite" the text. Useful for correcting misspellings or just replacing unwanted // code with new code. var end = position; if (start != position || alwaysExtendEndSpan) { while (end < text.Length && isWordCharacter(text[end])) { end++; } } return TextSpan.FromBounds(start, end); } public static bool IsStartingNewWord(SourceText text, int characterPosition, Func<char, bool> isWordStartCharacter, Func<char, bool> isWordCharacter) { var ch = text[characterPosition]; if (!isWordStartCharacter(ch)) { return false; } // Only want to trigger if we're the first character in an identifier. If there's a // character before or after us, then we don't want to trigger. if (characterPosition > 0 && isWordCharacter(text[characterPosition - 1])) { return false; } if (characterPosition < text.Length - 1 && isWordCharacter(text[characterPosition + 1])) { return false; } return true; } public static Func<CancellationToken, Task<CompletionDescription>> CreateDescriptionFactory( Workspace workspace, SemanticModel semanticModel, int position, ISymbol symbol) { return CreateDescriptionFactory(workspace, semanticModel, position, new[] { symbol }); } public static Func<CancellationToken, Task<CompletionDescription>> CreateDescriptionFactory( Workspace workspace, SemanticModel semanticModel, int position, IReadOnlyList<ISymbol> symbols) { return c => CreateDescriptionAsync(workspace, semanticModel, position, symbols, supportedPlatforms: null, cancellationToken: c); } public static Func<CancellationToken, Task<CompletionDescription>> CreateDescriptionFactory( Workspace workspace, SemanticModel semanticModel, int position, IReadOnlyList<ISymbol> symbols, SupportedPlatformData supportedPlatforms) { return c => CreateDescriptionAsync(workspace, semanticModel, position, symbols, supportedPlatforms: supportedPlatforms, cancellationToken: c); } public static async Task<CompletionDescription> CreateDescriptionAsync( Workspace workspace, SemanticModel semanticModel, int position, ISymbol symbol, int overloadCount, SupportedPlatformData supportedPlatforms, CancellationToken cancellationToken) { var symbolDisplayService = workspace.Services.GetLanguageServices(semanticModel.Language).GetService<ISymbolDisplayService>(); var formatter = workspace.Services.GetLanguageServices(semanticModel.Language).GetService<IDocumentationCommentFormattingService>(); // TODO(cyrusn): Figure out a way to cancel this. var sections = await symbolDisplayService.ToDescriptionGroupsAsync(workspace, semanticModel, position, ImmutableArray.Create(symbol), cancellationToken).ConfigureAwait(false); if (!sections.ContainsKey(SymbolDescriptionGroups.MainDescription)) { return CompletionDescription.Empty; } var textContentBuilder = new List<TaggedText>(); textContentBuilder.AddRange(sections[SymbolDescriptionGroups.MainDescription]); switch (symbol.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.NamedType: if (overloadCount > 0) { var isGeneric = symbol.GetArity() > 0; textContentBuilder.AddSpace(); textContentBuilder.AddPunctuation("("); textContentBuilder.AddPunctuation("+"); textContentBuilder.AddText(NonBreakingSpaceString + overloadCount.ToString()); AddOverloadPart(textContentBuilder, overloadCount, isGeneric); textContentBuilder.AddPunctuation(")"); } break; } AddDocumentationPart(textContentBuilder, symbol, semanticModel, position, formatter, cancellationToken); if (sections.TryGetValue(SymbolDescriptionGroups.AwaitableUsageText, out var parts)) { textContentBuilder.AddRange(parts); } if (sections.TryGetValue(SymbolDescriptionGroups.AnonymousTypes, out parts)) { if (!parts.IsDefaultOrEmpty) { textContentBuilder.AddLineBreak(); textContentBuilder.AddLineBreak(); textContentBuilder.AddRange(parts); } } if (supportedPlatforms != null) { textContentBuilder.AddLineBreak(); textContentBuilder.AddRange(supportedPlatforms.ToDisplayParts().ToTaggedText()); } return CompletionDescription.Create(textContentBuilder.AsImmutable()); } public static Task<CompletionDescription> CreateDescriptionAsync( Workspace workspace, SemanticModel semanticModel, int position, IReadOnlyList<ISymbol> symbols, SupportedPlatformData supportedPlatforms, CancellationToken cancellationToken) { // Lets try to find the first non-obsolete symbol (overload) and fall-back // to the first symbol if all are obsolete. var symbol = symbols.FirstOrDefault(s => !s.IsObsolete()) ?? symbols[0]; return CreateDescriptionAsync(workspace, semanticModel, position, symbol, overloadCount: symbols.Count - 1, supportedPlatforms, cancellationToken); } private static void AddOverloadPart(List<TaggedText> textContentBuilder, int overloadCount, bool isGeneric) { var text = isGeneric ? overloadCount == 1 ? FeaturesResources.generic_overload : FeaturesResources.generic_overloads : overloadCount == 1 ? FeaturesResources.overload : FeaturesResources.overloads_; textContentBuilder.AddText(NonBreakingSpaceString + text); } private static void AddDocumentationPart( List<TaggedText> textContentBuilder, ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter, CancellationToken cancellationToken) { var documentation = symbol.GetDocumentationParts(semanticModel, position, formatter, cancellationToken); if (documentation.Any()) { textContentBuilder.AddLineBreak(); textContentBuilder.AddRange(documentation); } } internal static bool IsTextualTriggerString(SourceText text, int characterPosition, string value) { // The character position starts at the last character of 'value'. So if 'value' has // length 1, then we don't want to move, if it has length 2 we want to move back one, // etc. characterPosition = characterPosition - value.Length + 1; for (var i = 0; i < value.Length; i++, characterPosition++) { if (characterPosition < 0 || characterPosition >= text.Length) { return false; } if (text[characterPosition] != value[i]) { return false; } } return true; } public static bool TryRemoveAttributeSuffix(ISymbol symbol, SyntaxContext context, out string name) { var isAttributeNameContext = context.IsAttributeNameContext; var syntaxFacts = context.GetLanguageService<ISyntaxFactsService>(); if (!isAttributeNameContext) { name = null; return false; } // Do the symbol textual check first. Then the more expensive symbolic check. if (!symbol.Name.TryGetWithoutAttributeSuffix(syntaxFacts.IsCaseSensitive, out name) || !symbol.IsAttribute()) { return false; } return true; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Core/Portable/SourceGeneration/GeneratedSyntaxTree.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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// A syntax tree created by a <see cref="ISourceGenerator"/> /// </summary> internal readonly struct GeneratedSyntaxTree { public SourceText Text { get; } public string HintName { get; } public SyntaxTree Tree { get; } public GeneratedSyntaxTree(string hintName, SourceText text, SyntaxTree tree) { this.Text = text; this.HintName = hintName; this.Tree = tree; } } }
// 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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// A syntax tree created by a <see cref="ISourceGenerator"/> /// </summary> internal readonly struct GeneratedSyntaxTree { public SourceText Text { get; } public string HintName { get; } public SyntaxTree Tree { get; } public GeneratedSyntaxTree(string hintName, SourceText text, SyntaxTree tree) { this.Text = text; this.HintName = hintName; this.Tree = tree; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Analyzers/CSharp/CodeFixes/OrderModifiers/CSharpOrderModifiersCodeFixProvider.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.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.OrderModifiers; namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.OrderModifiers), Shared] internal class CSharpOrderModifiersCodeFixProvider : AbstractOrderModifiersCodeFixProvider { private const string CS0267 = nameof(CS0267); // The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or 'void' [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpOrderModifiersCodeFixProvider() : base(CSharpSyntaxFacts.Instance, CSharpCodeStyleOptions.PreferredModifierOrder, CSharpOrderModifiersHelper.Instance) { } protected override ImmutableArray<string> FixableCompilerErrorIds { get; } = ImmutableArray.Create(CS0267); } }
// 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.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.OrderModifiers; namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.OrderModifiers), Shared] internal class CSharpOrderModifiersCodeFixProvider : AbstractOrderModifiersCodeFixProvider { private const string CS0267 = nameof(CS0267); // The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or 'void' [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpOrderModifiersCodeFixProvider() : base(CSharpSyntaxFacts.Instance, CSharpCodeStyleOptions.PreferredModifierOrder, CSharpOrderModifiersHelper.Instance) { } protected override ImmutableArray<string> FixableCompilerErrorIds { get; } = ImmutableArray.Create(CS0267); } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/EditorFeatures/VisualBasicTest/KeywordHighlighting/AccessorDeclarationHighlighterTests.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 Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class AccessorDeclarationHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(AccessorDeclarationHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestPropertyAccessorsSample1_1() As Task Await TestAsync(<Text> Class C Public Property Goo As Integer Implements IGoo.Goo {|Cursor:[|Get|]|} [|Return|] 1 [|End Get|] Private Set(value As Integer) Exit Property End Set End Property End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestPropertyAccessorsSample1_2() As Task Await TestAsync(<Text> Class C Public Property Goo As Integer Implements IGoo.Goo [|Get|] {|Cursor:[|Return|]|} 1 [|End Get|] Private Set(value As Integer) Exit Property End Set End Property End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestPropertyAccessorsSample1_3() As Task Await TestAsync(<Text> Class C Public Property Goo As Integer Implements IGoo.Goo [|Get|] [|Return|] 1 {|Cursor:[|End Get|]|} Private Set(value As Integer) Exit Property End Set End Property End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestPropertyAccessorsSample2_1() As Task Await TestAsync(<Text> Class C Public Property Goo As Integer Implements IGoo.Goo Get Return 1 End Get {|Cursor:[|Private Set|]|}(value As Integer) [|Exit Property|] [|End Set|] End Property End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestPropertyAccessorsSample2_2() As Task Await TestAsync(<Text> Class C Public Property Goo As Integer Implements IGoo.Goo Get Return 1 End Get [|Private Set|](value As Integer) {|Cursor:[|Exit Property|]|} [|End Set|] End Property End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestPropertyAccessorsSample2_3() As Task Await TestAsync(<Text> Class C Public Property Goo As Integer Implements IGoo.Goo Get Return 1 End Get [|Private Set|](value As Integer) [|Exit Property|] {|Cursor:[|End Set|]|} End Property End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample1_1() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo {|Cursor:[|AddHandler|]|}(value As EventHandler) [|Return|] [|End AddHandler|] RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample1_2() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo [|AddHandler|](value As EventHandler) {|Cursor:[|Return|]|} [|End AddHandler|] RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample1_3() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo [|AddHandler|](value As EventHandler) [|Return|] {|Cursor:[|End AddHandler|]|} RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample2_1() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo AddHandler(value As EventHandler) Return End AddHandler {|Cursor:[|RemoveHandler|]|}(value As EventHandler) [|End RemoveHandler|] RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample2_2() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo AddHandler(value As EventHandler) Return End AddHandler [|RemoveHandler|](value As EventHandler) {|Cursor:[|End RemoveHandler|]|} RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample3_1() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo AddHandler(value As EventHandler) Return End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler {|Cursor:[|RaiseEvent|]|}(sender As Object, e As EventArgs) [|End RaiseEvent|] End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample3_2() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo AddHandler(value As EventHandler) Return End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler [|RaiseEvent|](sender As Object, e As EventArgs) {|Cursor:[|End RaiseEvent|]|} End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestProperty_IteratorExample5_1() As Task Await TestAsync( <Text> ReadOnly Iterator Property Goo As IEnumerable(Of Integer) {|Cursor:[|Get|]|} [|Yield|] 1 [|End Get|] End Property </Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestProperty_IteratorExample5_2() As Task Await TestAsync( <Text> ReadOnly Iterator Property Goo As IEnumerable(Of Integer) [|Get|] {|Cursor:[|Yield|]|} 1 [|End Get|] End Property </Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestProperty_IteratorExample5_3() As Task Await TestAsync( <Text> ReadOnly Iterator Property Goo As IEnumerable(Of Integer) [|Get|] [|Yield|] 1 {|Cursor:[|End Get|]|} End Property </Text>) 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 Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class AccessorDeclarationHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(AccessorDeclarationHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestPropertyAccessorsSample1_1() As Task Await TestAsync(<Text> Class C Public Property Goo As Integer Implements IGoo.Goo {|Cursor:[|Get|]|} [|Return|] 1 [|End Get|] Private Set(value As Integer) Exit Property End Set End Property End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestPropertyAccessorsSample1_2() As Task Await TestAsync(<Text> Class C Public Property Goo As Integer Implements IGoo.Goo [|Get|] {|Cursor:[|Return|]|} 1 [|End Get|] Private Set(value As Integer) Exit Property End Set End Property End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestPropertyAccessorsSample1_3() As Task Await TestAsync(<Text> Class C Public Property Goo As Integer Implements IGoo.Goo [|Get|] [|Return|] 1 {|Cursor:[|End Get|]|} Private Set(value As Integer) Exit Property End Set End Property End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestPropertyAccessorsSample2_1() As Task Await TestAsync(<Text> Class C Public Property Goo As Integer Implements IGoo.Goo Get Return 1 End Get {|Cursor:[|Private Set|]|}(value As Integer) [|Exit Property|] [|End Set|] End Property End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestPropertyAccessorsSample2_2() As Task Await TestAsync(<Text> Class C Public Property Goo As Integer Implements IGoo.Goo Get Return 1 End Get [|Private Set|](value As Integer) {|Cursor:[|Exit Property|]|} [|End Set|] End Property End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestPropertyAccessorsSample2_3() As Task Await TestAsync(<Text> Class C Public Property Goo As Integer Implements IGoo.Goo Get Return 1 End Get [|Private Set|](value As Integer) [|Exit Property|] {|Cursor:[|End Set|]|} End Property End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample1_1() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo {|Cursor:[|AddHandler|]|}(value As EventHandler) [|Return|] [|End AddHandler|] RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample1_2() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo [|AddHandler|](value As EventHandler) {|Cursor:[|Return|]|} [|End AddHandler|] RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample1_3() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo [|AddHandler|](value As EventHandler) [|Return|] {|Cursor:[|End AddHandler|]|} RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample2_1() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo AddHandler(value As EventHandler) Return End AddHandler {|Cursor:[|RemoveHandler|]|}(value As EventHandler) [|End RemoveHandler|] RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample2_2() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo AddHandler(value As EventHandler) Return End AddHandler [|RemoveHandler|](value As EventHandler) {|Cursor:[|End RemoveHandler|]|} RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample3_1() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo AddHandler(value As EventHandler) Return End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler {|Cursor:[|RaiseEvent|]|}(sender As Object, e As EventArgs) [|End RaiseEvent|] End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestEventAccessorsSample3_2() As Task Await TestAsync(<Text> Class C Public Custom Event Goo As EventHandler Implements IGoo.Goo AddHandler(value As EventHandler) Return End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler [|RaiseEvent|](sender As Object, e As EventArgs) {|Cursor:[|End RaiseEvent|]|} End Event End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestProperty_IteratorExample5_1() As Task Await TestAsync( <Text> ReadOnly Iterator Property Goo As IEnumerable(Of Integer) {|Cursor:[|Get|]|} [|Yield|] 1 [|End Get|] End Property </Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestProperty_IteratorExample5_2() As Task Await TestAsync( <Text> ReadOnly Iterator Property Goo As IEnumerable(Of Integer) [|Get|] {|Cursor:[|Yield|]|} 1 [|End Get|] End Property </Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestProperty_IteratorExample5_3() As Task Await TestAsync( <Text> ReadOnly Iterator Property Goo As IEnumerable(Of Integer) [|Get|] [|Yield|] 1 {|Cursor:[|End Get|]|} End Property </Text>) End Function End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/EditorFeatures/Core/Extensibility/NavigationBar/NavigationBarDropdownKind.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.Editor { internal enum NavigationBarDropdownKind { Project = 0, Type = 1, Member = 2 } }
// 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.Editor { internal enum NavigationBarDropdownKind { Project = 0, Type = 1, Member = 2 } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./docs/compilers/CSharp/System.TypedReference.md
System.TypedReference ===================== [This is a placeholder. We need some more documentation here] This is an old email conversation that gives some context about the interop support in the C# compiler. Ironically, the conversation suggests that we'll never document it! ------------------- Subject: RE: error CS0610: Field or property cannot be of type 'System.TypedReference' From: Eric Lippert To: Aleksey Tsingauz; Neal Gafter; Roslyn Compiler Dev Team Sent: Monday, January 24, 2011 9:42 AM Basically what’s going on here is we have some undocumented features which enable you to pass around a reference to a **variable** without knowing the type of the variable at compile time. The reason why we have this feature is to enable C-style “varargs” in the CLR; you might have a method that takes an unspecified number of arguments and some of those arguments might be references to variables. Because a `TypedReference` can contain the address of a stack-allocated variable, you’re not allowed to store them in fields, same as you’re not allowed to make a field of ref type. That way we know we’re never storing a reference to a “dead” stack variable. We have a bunch of goo in the native compiler to make sure that typed references (and a few other similarly magical types) are not used incorrectly; we’ll have to do the same thing in Roslyn at some point. None of this stuff is well documented. We have four undocumented language keywords that allow you to manipulate typed references; we have no intention as far as I know of ever documenting them. They are only there for rare situations where C# code needs to interoperate with a C-style method. Some various articles on these features that might give you more background if you’re interested: http://www.eggheadcafe.com/articles/20030114.asp http://stackoverflow.com/questions/4764573/why-is-typedreference-behind-the-scenes-its-so-fast-and-safe-almost-magical http://stackoverflow.com/questions/1711393/practical-uses-of-typedreference http://stackoverflow.com/questions/2064509/c-type-parameters-specification http://stackoverflow.com/questions/4046397/generic-variadic-parameters http://bartdesmet.net/blogs/bart/archive/2006/09/28/4473.aspx Cheers, Eric --------------------- From: Aleksey Tsingauz Sent: Sunday, January 23, 2011 11:00 PM To: Neal Gafter; Roslyn Compiler Dev Team Subject: RE: error CS0610: Field or property cannot be of type 'System.TypedReference'   I believe it is about ECMA-335 §8.2.1.1 Managed pointers and related types:   A **managed pointer** (§12.1.1.2), or **byref** (§8.6.1.3, §12.4.1.5.2), can point to a local variable, parameter, field of a compound type, or element of an array. However, when a call crosses a remoting boundary (see §12.5) a conforming implementation can use a copy-in/copy-out mechanism instead of a managed pointer. Thus programs shall not rely on the aliasing behavior of true pointers. Managed pointer types are only allowed for local variable (§8.6.1.3) and parameter signatures (§8.6.1.4); they cannot be used for field signatures (§8.6.1.2), as the element type of an array (§8.9.1), and boxing a value of managed pointer type is disallowed (§8.2.4). Using a managed pointer type for the return type of methods (§8.6.1.5) is not verifiable (§8.8). [Rationale: For performance reasons items on the GC heap may not contain references to the interior of other GC objects, this motivates the restrictions on fields and boxing. Further returning a managed pointer which references a local or parameter variable may cause the reference to outlive the variable, hence it is not verifiable . end rationale] There are three value types in the Base Class Library (see Partition IV Library): `System.TypedReference`, `System.RuntimeArgumentHandle`, and `System.ArgIterator`; which are treated specially by the CLI. The value type `System.TypedReference`, or *typed reference* or *typedref* , (§8.2.2, §8.6.1.3, §12.4.1.5.3) contains both a managed pointer to a location and a runtime representation of the type that can be stored at that location. Typed references have the same restrictions as byrefs. Typed references are created by the CIL instruction `mkrefany` (see Partition III). The value types `System.RuntimeArgumentHandle` and `System.ArgIterator` (see Partition IV and CIL instruction `arglist` in Partition III), contain pointers into the VES stack. They can be used for local variable and parameter signatures. The use of these types for fields, method return types, the element type of an array, or in boxing is not verifiable (§8.8). These two types are referred to as *byref-like* types. ---------------- From: Neal Gafter Sent: Sunday, January 23, 2011 8:37 PM To: Roslyn Compiler Dev Team Cc: Neal Gafter Subject: error CS0610: Field or property cannot be of type 'System.TypedReference'   What is this error all about?  Where is it documented?
System.TypedReference ===================== [This is a placeholder. We need some more documentation here] This is an old email conversation that gives some context about the interop support in the C# compiler. Ironically, the conversation suggests that we'll never document it! ------------------- Subject: RE: error CS0610: Field or property cannot be of type 'System.TypedReference' From: Eric Lippert To: Aleksey Tsingauz; Neal Gafter; Roslyn Compiler Dev Team Sent: Monday, January 24, 2011 9:42 AM Basically what’s going on here is we have some undocumented features which enable you to pass around a reference to a **variable** without knowing the type of the variable at compile time. The reason why we have this feature is to enable C-style “varargs” in the CLR; you might have a method that takes an unspecified number of arguments and some of those arguments might be references to variables. Because a `TypedReference` can contain the address of a stack-allocated variable, you’re not allowed to store them in fields, same as you’re not allowed to make a field of ref type. That way we know we’re never storing a reference to a “dead” stack variable. We have a bunch of goo in the native compiler to make sure that typed references (and a few other similarly magical types) are not used incorrectly; we’ll have to do the same thing in Roslyn at some point. None of this stuff is well documented. We have four undocumented language keywords that allow you to manipulate typed references; we have no intention as far as I know of ever documenting them. They are only there for rare situations where C# code needs to interoperate with a C-style method. Some various articles on these features that might give you more background if you’re interested: http://www.eggheadcafe.com/articles/20030114.asp http://stackoverflow.com/questions/4764573/why-is-typedreference-behind-the-scenes-its-so-fast-and-safe-almost-magical http://stackoverflow.com/questions/1711393/practical-uses-of-typedreference http://stackoverflow.com/questions/2064509/c-type-parameters-specification http://stackoverflow.com/questions/4046397/generic-variadic-parameters http://bartdesmet.net/blogs/bart/archive/2006/09/28/4473.aspx Cheers, Eric --------------------- From: Aleksey Tsingauz Sent: Sunday, January 23, 2011 11:00 PM To: Neal Gafter; Roslyn Compiler Dev Team Subject: RE: error CS0610: Field or property cannot be of type 'System.TypedReference'   I believe it is about ECMA-335 §8.2.1.1 Managed pointers and related types:   A **managed pointer** (§12.1.1.2), or **byref** (§8.6.1.3, §12.4.1.5.2), can point to a local variable, parameter, field of a compound type, or element of an array. However, when a call crosses a remoting boundary (see §12.5) a conforming implementation can use a copy-in/copy-out mechanism instead of a managed pointer. Thus programs shall not rely on the aliasing behavior of true pointers. Managed pointer types are only allowed for local variable (§8.6.1.3) and parameter signatures (§8.6.1.4); they cannot be used for field signatures (§8.6.1.2), as the element type of an array (§8.9.1), and boxing a value of managed pointer type is disallowed (§8.2.4). Using a managed pointer type for the return type of methods (§8.6.1.5) is not verifiable (§8.8). [Rationale: For performance reasons items on the GC heap may not contain references to the interior of other GC objects, this motivates the restrictions on fields and boxing. Further returning a managed pointer which references a local or parameter variable may cause the reference to outlive the variable, hence it is not verifiable . end rationale] There are three value types in the Base Class Library (see Partition IV Library): `System.TypedReference`, `System.RuntimeArgumentHandle`, and `System.ArgIterator`; which are treated specially by the CLI. The value type `System.TypedReference`, or *typed reference* or *typedref* , (§8.2.2, §8.6.1.3, §12.4.1.5.3) contains both a managed pointer to a location and a runtime representation of the type that can be stored at that location. Typed references have the same restrictions as byrefs. Typed references are created by the CIL instruction `mkrefany` (see Partition III). The value types `System.RuntimeArgumentHandle` and `System.ArgIterator` (see Partition IV and CIL instruction `arglist` in Partition III), contain pointers into the VES stack. They can be used for local variable and parameter signatures. The use of these types for fields, method return types, the element type of an array, or in boxing is not verifiable (§8.8). These two types are referred to as *byref-like* types. ---------------- From: Neal Gafter Sent: Sunday, January 23, 2011 8:37 PM To: Roslyn Compiler Dev Team Cc: Neal Gafter Subject: error CS0610: Field or property cannot be of type 'System.TypedReference'   What is this error all about?  Where is it documented?
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_MarshalAs.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 Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Imports Xunit Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_MarshalAs Inherits BasicTestBase #Region "Helpers" Private Sub VerifyFieldMetadataDecoding(verifier As CompilationVerifier, blobs As Dictionary(Of String, Byte())) Dim count = 0 Using assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData) Dim c = VisualBasicCompilation.Create("c", syntaxTrees:=New VisualBasicSyntaxTree() {}, references:={assembly.GetReference()}) For Each typeSym As NamedTypeSymbol In c.GlobalNamespace.GetMembers().Where(Function(s) s.Kind = SymbolKind.NamedType) Dim fields = typeSym.GetMembers().Where(Function(s) s.Kind = SymbolKind.Field) For Each field As FieldSymbol In fields Assert.Null(field.MarshallingInformation) Dim blob = blobs(field.Name) If blob IsNot Nothing AndAlso blob(0) <= &H50 Then Assert.Equal(CType(blob(0), UnmanagedType), field.MarshallingType) Else Assert.Equal(CType(0, UnmanagedType), field.MarshallingType) End If count = count + 1 Next Next End Using Assert.True(count > 0, "Expected at least one field") End Sub Private Sub VerifyParameterMetadataDecoding(verifier As CompilationVerifier, blobs As Dictionary(Of String, Byte())) Dim count = 0 Using assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData) Dim c = VisualBasicCompilation.Create("c", syntaxTrees:=New VisualBasicSyntaxTree() {}, references:={assembly.GetReference()}) For Each typeSym As NamedTypeSymbol In c.GlobalNamespace.GetMembers().Where(Function(s) s.Kind = SymbolKind.NamedType) Dim methods = typeSym.GetMembers().Where(Function(s) s.Kind = SymbolKind.Method) For Each method As MethodSymbol In methods For Each parameter In method.Parameters Assert.Null(parameter.MarshallingInformation) Dim blob = blobs(method.Name & ":" & parameter.Name) If blob IsNot Nothing AndAlso blob(0) <= &H50 Then Assert.Equal(CType(blob(0), UnmanagedType), parameter.MarshallingType) Else Assert.Equal(CType(0, UnmanagedType), parameter.MarshallingType) End If count = count + 1 Next Next Next End Using Assert.True(count > 0, "Expected at least one parameter") End Sub #End Region ''' <summary> ''' type only, others ignored, field type ignored ''' </summary> <Fact> Public Sub SimpleTypes() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(CShort(0))> Public ZeroShort As X <MarshalAs(DirectCast(0, UnmanagedType))> Public Zero As X <MarshalAs(DirectCast(&H1FFFFFFF, UnmanagedType))> Public MaxValue As X <MarshalAs(DirectCast((&H123456), UnmanagedType))> Public _0x123456 As X <MarshalAs(DirectCast((&H1000), UnmanagedType))> Public _0x1000 As X <MarshalAs(UnmanagedType.AnsiBStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public AnsiBStr As X <MarshalAs(UnmanagedType.AsAny, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public AsAny As Double <MarshalAs(UnmanagedType.Bool, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public Bool As X <MarshalAs(UnmanagedType.BStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public BStr As X <MarshalAs(UnmanagedType.Currency, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public Currency As Integer <MarshalAs(UnmanagedType.[Error], ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public [Error] As Integer <MarshalAs(UnmanagedType.FunctionPtr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public FunctionPtr As Integer <MarshalAs(UnmanagedType.I1, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I1 As Integer <MarshalAs(UnmanagedType.I2, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I2 As Integer <MarshalAs(UnmanagedType.I4, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I4 As Integer <MarshalAs(UnmanagedType.I8, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I8 As Integer <MarshalAs(UnmanagedType.LPStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPStr As Integer <MarshalAs(UnmanagedType.LPStruct, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPStruct As Integer <MarshalAs(UnmanagedType.LPTStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPTStr As Integer <MarshalAs(UnmanagedType.LPWStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPWStr As Integer <MarshalAs(UnmanagedType.R4, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public R4 As Integer <MarshalAs(UnmanagedType.R8, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public R8 As Integer <MarshalAs(UnmanagedType.Struct, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public Struct As Integer <MarshalAs(UnmanagedType.SysInt, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public SysInt As Decimal <MarshalAs(UnmanagedType.SysUInt, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public SysUInt As Integer() <MarshalAs(UnmanagedType.TBStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public TBStr As Object() <MarshalAs(UnmanagedType.U1, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U1 As Integer <MarshalAs(UnmanagedType.U2, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U2 As Double <MarshalAs(UnmanagedType.U4, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U4 As Boolean <MarshalAs(UnmanagedType.U8, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U8 As String <MarshalAs(UnmanagedType.VariantBool, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public VariantBool As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"ZeroShort", New Byte() {&H0}}, {"Zero", New Byte() {&H0}}, {"MaxValue", New Byte() {&HDF, &HFF, &HFF, &HFF}}, {"_0x1000", New Byte() {&H90, &H0}}, {"_0x123456", New Byte() {&HC0, &H12, &H34, &H56}}, {"AnsiBStr", New Byte() {&H23}}, {"AsAny", New Byte() {&H28}}, {"Bool", New Byte() {&H2}}, {"BStr", New Byte() {&H13}}, {"Currency", New Byte() {&HF}}, {"Error", New Byte() {&H2D}}, {"FunctionPtr", New Byte() {&H26}}, {"I1", New Byte() {&H3}}, {"I2", New Byte() {&H5}}, {"I4", New Byte() {&H7}}, {"I8", New Byte() {&H9}}, {"LPStr", New Byte() {&H14}}, {"LPStruct", New Byte() {&H2B}}, {"LPTStr", New Byte() {&H16}}, {"LPWStr", New Byte() {&H15}}, {"R4", New Byte() {&HB}}, {"R8", New Byte() {&HC}}, {"Struct", New Byte() {&H1B}}, {"SysInt", New Byte() {&H1F}}, {"SysUInt", New Byte() {&H20}}, {"TBStr", New Byte() {&H24}}, {"U1", New Byte() {&H4}}, {"U2", New Byte() {&H6}}, {"U4", New Byte() {&H8}}, {"U8", New Byte() {&HA}}, {"VariantBool", New Byte() {&H25}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub SimpleTypes_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Class X <MarshalAs(CType(-1, UnmanagedType))> Dim MinValue_1 As X <MarshalAs(CType(&H20000000, UnmanagedType))> Dim MaxValue_1 As X End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttribute1, "CType(-1, UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "CType(&H20000000, UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (type, IidParamIndex), others ignored, field type ignored ''' </summary> <Fact> Public Sub ComInterfaces() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.IDispatch, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=0, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public IDispatch As Byte <MarshalAs(UnmanagedType.[Interface], ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public [Interface] As X <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=2, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public IUnknown As X() <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H1FFFFFFF, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public MaxValue As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H123456, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public m_123456 As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H1000, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public m_0x1000 As X <MarshalAs(UnmanagedType.IDispatch)> Public [Default] As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"IDispatch", New Byte() {&H1A, &H0}}, {"Interface", New Byte() {&H1C, &H1}}, {"IUnknown", New Byte() {&H19, &H2}}, {"MaxValue", New Byte() {&H19, &HDF, &HFF, &HFF, &HFF}}, {"m_123456", New Byte() {&H19, &HC0, &H12, &H34, &H56}}, {"m_0x1000", New Byte() {&H19, &H90, &H0}}, {"Default", New Byte() {&H1A}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub ComInterfaces_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Class X <MarshalAs(UnmanagedType.IDispatch, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim IDispatch_MinValue_1 As Integer <MarshalAs(UnmanagedType.[Interface], ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim Interface_MinValue_1 As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim IUnknown_MinValue_1 As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H20000000, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim IUnknown_MaxValue_1 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=&H20000000").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (ArraySubType, SizeConst, SizeParamIndex), SafeArraySubType not allowed, others ignored ''' </summary> <Fact> Public Sub NativeTypeArray() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.LPArray)> Public LPArray0 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public LPArray1 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=0, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public LPArray2 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=&H1FFFFFFF, SizeParamIndex:=Short.MaxValue, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public LPArray3 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(&H50, UnmanagedType))> Public LPArray4 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(&H1FFFFFFF, UnmanagedType))> Public LPArray5 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(0, UnmanagedType))> Public LPArray6 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"LPArray0", New Byte() {&H2A, &H50}}, {"LPArray1", New Byte() {&H2A, &H17}}, {"LPArray2", New Byte() {&H2A, &H17, &H0, &H0, &H0}}, {"LPArray3", New Byte() {&H2A, &H17, &HC0, &H0, &H7F, &HFF, &HDF, &HFF, &HFF, &HFF, &H1}}, {"LPArray4", New Byte() {&H2A, &H50}}, {"LPArray5", New Byte() {&H2A, &HDF, &HFF, &HFF, &HFF}}, {"LPArray6", New Byte() {&H2A, &H0}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeArray_ElementTypes() Dim source As StringBuilder = New StringBuilder(<text> Imports System Imports System.Runtime.InteropServices Class X </text>.Value) Dim expectedBlobs = New Dictionary(Of String, Byte())() For i = 0 To SByte.MaxValue If i <> DirectCast(UnmanagedType.CustomMarshaler, Integer) Then Dim fldName As String = String.Format("m_{0:X}", i) source.AppendLine(String.Format("<MarshalAs(UnmanagedType.LPArray, ArraySubType := CType(&H{0:X}, UnmanagedType))>Dim {1} As Integer", i, fldName)) expectedBlobs.Add(fldName, New Byte() {&H2A, CByte(i)}) End If Next source.AppendLine("End Class") CompileAndVerifyFieldMarshal(source.ToString(), expectedBlobs) End Sub <Fact()> Public Sub NativeTypeArray_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class X <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim LPArray_e0 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=-1)> Dim LPArray_e1 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=0, SizeParamIndex:=-1)> Dim LPArray_e2 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=Int32.MaxValue, SizeParamIndex:=Int16.MaxValue)> Dim LPArray_e3 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.U8, SizeConst:=Int32.MaxValue / 4 + 1, SizeParamIndex:=Int16.MaxValue)> Dim LPArray_e4 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.CustomMarshaler)> Dim LPArray_e5 As Integer <MarshalAs(UnmanagedType.LPArray, SafeArraySubType:=VarEnum.VT_I1)> Dim LPArray_e6 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(&H20000000, UnmanagedType))> Dim LPArray_e7 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast((-1), UnmanagedType))> Dim LPArray_e8 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_BSTR"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeParamIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeParamIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=Int32.MaxValue").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=Int32.MaxValue / 4 + 1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "ArraySubType:=UnmanagedType.CustomMarshaler").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_I1"), Diagnostic(ERRID.ERR_BadAttribute1, "ArraySubType:=DirectCast(&H20000000, UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "ArraySubType:=DirectCast((-1), UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (ArraySubType, SizeConst), (SizeParamIndex, SafeArraySubType) not allowed, others ignored ''' </summary> <Fact> Public Sub NativeTypeFixedArray() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValArray)> Public ByValArray0 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public ByValArray1 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=0, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public ByValArray2 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=(Int32.MaxValue - 3) / 4, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public ByValArray3 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.AsAny)> Public ByValArray4 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.CustomMarshaler)> Public ByValArray5 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"ByValArray0", New Byte() {&H1E, &H1}}, {"ByValArray1", New Byte() {&H1E, &H1, &H17}}, {"ByValArray2", New Byte() {&H1E, &H0, &H17}}, {"ByValArray3", New Byte() {&H1E, &HDF, &HFF, &HFF, &HFF, &H17}}, {"ByValArray4", New Byte() {&H1E, &H1, &H28}}, {"ByValArray5", New Byte() {&H1E, &H1, &H2C}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeFixedArray_ElementTypes() Dim source As StringBuilder = New StringBuilder(<text> Imports System Imports System.Runtime.InteropServices Class X </text>.Value) Dim expectedBlobs = New Dictionary(Of String, Byte())() Dim i As Integer = 0 While i < SByte.MaxValue Dim fldName As String = String.Format("m_{0:X}", i) source.AppendLine(String.Format("<MarshalAs(UnmanagedType.ByValArray, ArraySubType := CType(&H{0:X}, UnmanagedType))>Dim {1} As Integer", i, fldName)) expectedBlobs.Add(fldName, New Byte() {&H1E, &H1, CByte(i)}) i = i + 1 End While source.AppendLine("End Class") CompileAndVerifyFieldMarshal(source.ToString(), expectedBlobs) End Sub <Fact()> Public Sub NativeTypeFixedArray_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim ByValArray_e1 As Integer <MarshalAs(UnmanagedType.ByValArray, SizeParamIndex:=Int16.MaxValue)> Dim ByValArray_e2 As Integer <MarshalAs(UnmanagedType.ByValArray, SafeArraySubType:=VarEnum.VT_I2)> Dim ByValArray_e3 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=&H20000000)> Dim ByValArray_e4 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_BSTR"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=-1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=Int16.MaxValue"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_I2"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=&H20000000").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (SafeArraySubType, SafeArrayUserDefinedSubType), (ArraySubType, SizeConst, SizeParamIndex) not allowed, ''' (SafeArraySubType, SafeArrayUserDefinedSubType) not allowed together unless VT_DISPATCH, VT_UNKNOWN, VT_RECORD; others ignored. ''' </summary> <Fact> Public Sub NativeTypeSafeArray() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.SafeArray)> Public SafeArray0 As Integer <MarshalAs(UnmanagedType.SafeArray, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR)> Public SafeArray1 As Integer <MarshalAs(UnmanagedType.SafeArray, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=GetType(X))> Public SafeArray2 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=Nothing)> Public SafeArray3 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=GetType(Void))> Public SafeArray4 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_EMPTY)> Public SafeArray8 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(Integer()()))> Public SafeArray9 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(Nullable(Of)))> Public SafeArray10 As Integer End Class ]]> </file> </compilation> Dim aqn = Encoding.ASCII.GetBytes("System.Int32[][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") Dim openGenericAqn = Encoding.ASCII.GetBytes("System.Nullable`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") Dim blobs = New Dictionary(Of String, Byte()) From { {"SafeArray0", New Byte() {&H1D}}, {"SafeArray1", New Byte() {&H1D, &H8}}, {"SafeArray2", New Byte() {&H1D}}, {"SafeArray3", New Byte() {&H1D}}, {"SafeArray4", New Byte() {&H1D}}, {"SafeArray8", New Byte() {&H1D, &H0}}, {"SafeArray9", New Byte() {&H1D, &H24, CByte(aqn.Length)}.Append(aqn)}, {"SafeArray10", New Byte() {&H1D, &H24, CByte(openGenericAqn.Length)}.Append(openGenericAqn)} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub NativeTypeSafeArray_CCIOnly() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Public Class C(Of T) Public Class D(Of S) Public Class E End Class End Class End Class Public Class X <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(C(Of Integer).D(Of Boolean).E))> Public SafeArray11 As Integer End Class ]]> </file> </compilation> Dim nestedAqn = Encoding.ASCII.GetBytes("C`1+D`1+E[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") Dim blobs = New Dictionary(Of String, Byte()) From { {"SafeArray11", New Byte() {&H1D, &H24, &H80, &HC4}.Append(nestedAqn)} } ' RefEmit has slightly different encoding of the type name Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeSafeArray_RefEmitDiffers() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_DISPATCH, SafeArrayUserDefinedSubType:=GetType(List(Of X)()()))> Dim SafeArray5 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_UNKNOWN, SafeArrayUserDefinedSubType:=GetType(X))> Dim SafeArray6 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(X))> Dim SafeArray7 As Integer End Class ]]>.Value Dim e = Encoding.ASCII Dim cciBlobs = New Dictionary(Of String, Byte()) From { {"SafeArray5", New Byte() {&H1D, &H9, &H75}.Append(e.GetBytes("System.Collections.Generic.List`1[X][][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"))}, {"SafeArray6", New Byte() {&H1D, &HD, &H1, &H58}}, {"SafeArray7", New Byte() {&H1D, &H24, &H1, &H58}} } CompileAndVerifyFieldMarshal(source, cciBlobs) End Sub <Fact()> Public Sub NativeTypeSafeArray_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.SafeArray, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim SafeArray_e1 As Integer <MarshalAs(UnmanagedType.SafeArray, ArraySubType:=UnmanagedType.ByValTStr)> Dim SafeArray_e2 As Integer <MarshalAs(UnmanagedType.SafeArray, SizeConst:=1)> Dim SafeArray_e3 As Integer <MarshalAs(UnmanagedType.SafeArray, SizeParamIndex:=1)> Dim SafeArray_e4 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing)> Dim SafeArray_e5 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=Nothing, SafeArraySubType:=VarEnum.VT_BLOB)> Dim SafeArray_e6 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=GetType(Integer), SafeArraySubType:=0)> Dim SafeArray_e7 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeConst:=-1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=-1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=Nothing"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeConst:=1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=Nothing"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=Nothing"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=GetType(Integer)")) End Sub ''' <summary> ''' (SizeConst - required), (SizeParamIndex, ArraySubType) not allowed ''' </summary> <Fact> Public Sub NativeTypeFixedSysString() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> Public ByValTStr1 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=&H1FFFFFFF, SafeArrayUserDefinedSubType:=GetType(Integer), IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing)> Public ByValTStr2 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"ByValTStr1", New Byte() {&H17, &H1}}, {"ByValTStr2", New Byte() {&H17, &HDF, &HFF, &HFF, &HFF}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeFixedSysString_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValTStr, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim ByValTStr_e1 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=-1)> Dim ByValTStr_e2 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=(Int32.MaxValue - 3) / 4 + 1)> Dim ByValTStr_e3 As Integer <MarshalAs(UnmanagedType.ByValTStr)> Dim ByValTStr_e4 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1, SizeParamIndex:=1)> Dim ByValTStr_e5 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1, ArraySubType:=UnmanagedType.ByValTStr)> Dim ByValTStr_e6 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1, SafeArraySubType:=VarEnum.VT_BSTR)> Dim ByValTStr_e7 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=-1"), Diagnostic(ERRID.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=(Int32.MaxValue - 3) / 4 + 1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr")) End Sub ''' <summary> ''' Custom (MarshalType, MarshalTypeRef, MarshalCookie) one of {MarshalType, MarshalTypeRef} required, others ignored ''' </summary> <Fact> Public Sub CustomMarshal() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Public Class X <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=Nothing)> Public CustomMarshaler1 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=Nothing)> Public CustomMarshaler2 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="foo", MarshalTypeRef:=GetType(Integer))> Public CustomMarshaler3 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=ChrW(&H1234) & "f" & ChrW(0) & "oozzz")> Public CustomMarshaler4 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="f" & ChrW(0) & "oozzz")> Public CustomMarshaler5 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")> Public CustomMarshaler6 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public CustomMarshaler7 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=GetType(Integer))> Public CustomMarshaler8 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=GetType(Integer), MarshalType:="foo", MarshalCookie:="hello" & ChrW(0) & "world(" & ChrW(&H1234) & ")")> Public CustomMarshaler9 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=Nothing, MarshalTypeRef:=GetType(Integer))> Public CustomMarshaler10 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="foo", MarshalTypeRef:=Nothing)> Public CustomMarshaler11 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=Nothing, MarshalTypeRef:=Nothing)> Public CustomMarshaler12 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="aaa" & ChrW(0) & "bbb", MarshalCookie:="ccc" & ChrW(0) & "ddd")> Public CustomMarshaler13 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=ChrW(&HD869) & ChrW(&HDED6), MarshalCookie:=ChrW(&HD869) & ChrW(&HDED6))> Public CustomMarshaler14 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"CustomMarshaler1", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler2", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler3", New Byte() {&H2C, &H0, &H0, &H3, &H66, &H6F, &H6F, &H0}}, {"CustomMarshaler4", New Byte() {&H2C, &H0, &H0, &HA, &HE1, &H88, &HB4, &H66, &H0, &H6F, &H6F, &H7A, &H7A, &H7A, &H0}}, {"CustomMarshaler5", New Byte() {&H2C, &H0, &H0, &H7, &H66, &H0, &H6F, &H6F, &H7A, &H7A, &H7A, &H0}}, {"CustomMarshaler6", New Byte() {&H2C, &H0, &H0, &H60}.Append(Encoding.UTF8.GetBytes("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" & ChrW(0)))}, {"CustomMarshaler7", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler8", New Byte() {&H2C, &H0, &H0, &H59}.Append(Encoding.UTF8.GetBytes("System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" & ChrW(0)))}, {"CustomMarshaler9", New Byte() {&H2C, &H0, &H0, &H3, &H66, &H6F, &H6F, &H10, &H68, &H65, &H6C, &H6C, &H6F, &H0, &H77, &H6F, &H72, &H6C, &H64, &H28, &HE1, &H88, &HB4, &H29}}, {"CustomMarshaler10", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler11", New Byte() {&H2C, &H0, &H0, &H3, &H66, &H6F, &H6F, &H0}}, {"CustomMarshaler12", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler13", New Byte() {&H2C, &H0, &H0, &H7, &H61, &H61, &H61, &H0, &H62, &H62, &H62, &H7, &H63, &H63, &H63, &H0, &H64, &H64, &H64}}, {"CustomMarshaler14", New Byte() {&H2C, &H0, &H0, &H4, &HF0, &HAA, &H9B, &H96, &H4, &HF0, &HAA, &H9B, &H96}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub CustomMarshal_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Public Class X <MarshalAs(UnmanagedType.CustomMarshaler)> Dim CustomMarshaler_e0 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="a" & ChrW(&HDC00) & "b", MarshalCookie:="b")> Dim CustomMarshaler_e1 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="x", MarshalCookie:="y" & ChrW(&HDC00))> Dim CustomMarshaler_e2 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_AttributeParameterRequired2, "MarshalAs").WithArguments("MarshalType", "MarshalTypeRef"), Diagnostic(ERRID.ERR_BadAttribute1, "MarshalType:=""a"" & ChrW(&HDC00) & ""b""").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "MarshalCookie:=""y"" & ChrW(&HDC00)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub <Fact()> Public Sub Events_Error() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class C <MarshalAs(UnmanagedType.Bool)> Event e As Action End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "MarshalAs").WithArguments("MarshalAsAttribute", "e")) End Sub <Fact()> Public Sub MarshalAs_AllFieldTargets() Dim source = <compilation><file><![CDATA[ Imports System Imports System.Runtime.InteropServices Class Z <MarshalAs(UnmanagedType.Bool)> Dim f As Integer End Class Module M <MarshalAs(UnmanagedType.Bool)> Public WithEvents we As New Z End Module Enum En <MarshalAs(UnmanagedType.Bool)> A = 1 <MarshalAs(UnmanagedType.Bool)> B End Enum ]]></file></compilation> CompileAndVerifyFieldMarshal(source, Function(name, _omitted1) Return If(name = "f" Or name = "_we" Or name = "A" Or name = "B", New Byte() {&H2}, Nothing) End Function) End Sub <Fact()> Public Sub Parameters() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Class X Public Shared Function foo(<MarshalAs(UnmanagedType.IDispatch)> ByRef IDispatch As Integer, <MarshalAs(UnmanagedType.LPArray)> ByRef LPArray0 As Integer, <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_EMPTY)> SafeArray8 As Integer, <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="aaa" & ChrW(0) & "bbb", MarshalCookie:="ccc" & ChrW(0) & "ddd")> CustomMarshaler13 As Integer) As <MarshalAs(UnmanagedType.LPStr)> X Return Nothing End Function End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {"foo:", New Byte() {&H14}}, {"foo:IDispatch", New Byte() {&H1A}}, {"foo:LPArray0", New Byte() {&H2A, &H50}}, {"foo:SafeArray8", New Byte() {&H1D, &H0}}, {"foo:CustomMarshaler13", New Byte() {&H2C, &H0, &H0, &H7, &H61, &H61, &H61, &H0, &H62, &H62, &H62, &H7, &H63, &H63, &H63, &H0, &H64, &H64, &H64}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Events() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module X Custom Event E As Action AddHandler(<MarshalAs(UnmanagedType.BStr)> eAdd As Action) End AddHandler RemoveHandler(<MarshalAs(UnmanagedType.BStr)> eRemove As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Module ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {"add_E:eAdd", New Byte() {&H13}}, {"remove_E:eRemove", New Byte() {&H13}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Properties() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module C Property P(<MarshalAs(UnmanagedType.I2)> pIndex As Integer) As <MarshalAs(UnmanagedType.I4)> Integer Get Return 0 End Get Set(<MarshalAs(UnmanagedType.I8)> pValue As Integer) End Set End Property Property Q As <MarshalAs(UnmanagedType.I4)> Integer Get Return 0 End Get Set(qValue As Integer) End Set End Property Property CRW As <MarshalAs(UnmanagedType.I4)> Integer WriteOnly Property CW As <MarshalAs(UnmanagedType.I4)> Integer Set(sValue As Integer) End Set End Property ReadOnly Property CR As <MarshalAs(UnmanagedType.I4)> Integer Get Return 0 End Get End Property End Module Interface I Property IRW As <MarshalAs(UnmanagedType.I4)> Integer ReadOnly Property IR As <MarshalAs(UnmanagedType.I4)> Integer WriteOnly Property IW As <MarshalAs(UnmanagedType.I4)> Integer Property IRW2(a As Integer, b As Integer) As <MarshalAs(UnmanagedType.I4)> Integer ReadOnly Property IR2(a As Integer, b As Integer) As <MarshalAs(UnmanagedType.I4)> Integer WriteOnly Property IW2(a As Integer, b As Integer) As <MarshalAs(UnmanagedType.I4)> Integer End Interface ]]> </file> </compilation> Dim i2 = New Byte() {&H5} Dim i4 = New Byte() {&H7} Dim i8 = New Byte() {&H9} ' Dev11 incorrectly applies return-type MarshalAs on the first parameter of an interface property. Dim blobs = New Dictionary(Of String, Byte())() From { {"get_P:", i4}, {"get_P:pIndex", i2}, {"set_P:pIndex", i2}, {"set_P:pValue", i8}, {"get_Q:", i4}, {"set_Q:qValue", Nothing}, {"get_CRW:", i4}, {"set_CRW:AutoPropertyValue", Nothing}, {"set_CW:sValue", Nothing}, {"get_CR:", i4}, {"get_IRW:", i4}, {"set_IRW:Value", i4}, {"get_IR:", i4}, {"set_IW:Value", i4}, {"get_IRW2:", i4}, {"get_IRW2:a", Nothing}, {"get_IRW2:b", Nothing}, {"set_IRW2:a", Nothing}, {"set_IRW2:b", Nothing}, {"set_IRW2:Value", i4}, {"get_IR2:", i4}, {"get_IR2:a", Nothing}, {"get_IR2:b", Nothing}, {"set_IW2:a", Nothing}, {"set_IW2:b", Nothing}, {"set_IW2:Value", i4} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) CompilationUtils.AssertTheseDiagnostics(verifier.Compilation, <errors><![CDATA[ BC42364: Attributes applied on a return type of a WriteOnly Property have no effect. WriteOnly Property CW As <MarshalAs(UnmanagedType.I4)> Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_PropertyReturnType_MissingAccessors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module C Property Q As <MarshalAs(UnmanagedType.I4)> Integer End Property End Module ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c, <errors><![CDATA[ BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'. Property Q As <MarshalAs(UnmanagedType.I4)> Integer ~ ]]></errors>) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_PartialSubs() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Partial Class X Private Partial Sub F(<MarshalAs(UnmanagedType.BStr)> pf As Integer) End Sub Private Sub F(pf As Integer) End Sub Private Partial Sub G(pg As Integer) End Sub Private Sub G(<MarshalAs(UnmanagedType.BStr)> pg As Integer) End Sub Private Sub H(<MarshalAs(UnmanagedType.BStr)> ph As Integer) End Sub Private Partial Sub H(ph As Integer) End Sub Private Sub I(pi As Integer) End Sub Private Partial Sub I(<MarshalAs(UnmanagedType.BStr)> pi As Integer) End Sub End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {"F:pf", New Byte() {&H13}}, {"G:pg", New Byte() {&H13}}, {"H:ph", New Byte() {&H13}}, {"I:pi", New Byte() {&H13}} } CompileAndVerifyFieldMarshal(source, blobs, isField:=False) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Delegate() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Delegate Function D(<MarshalAs(UnmanagedType.BStr)>p As Integer, <MarshalAs(UnmanagedType.BStr)>ByRef q As Integer) As <MarshalAs(UnmanagedType.BStr)> Integer ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {".ctor:TargetObject", Nothing}, {".ctor:TargetMethod", Nothing}, {"BeginInvoke:p", New Byte() {&H13}}, {"BeginInvoke:q", New Byte() {&H13}}, {"BeginInvoke:DelegateCallback", Nothing}, {"BeginInvoke:DelegateAsyncState", Nothing}, {"EndInvoke:p", New Byte() {&H13}}, {"EndInvoke:q", New Byte() {&H13}}, {"EndInvoke:DelegateAsyncResult", Nothing}, {"Invoke:", New Byte() {&H13}}, {"Invoke:p", New Byte() {&H13}}, {"Invoke:q", New Byte() {&H13}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Declare() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module M Declare Function Foo Lib "foo" ( <MarshalAs(UnmanagedType.BStr)> explicitInt As Integer, <MarshalAs(UnmanagedType.BStr)> ByRef explicitByRefInt As Integer, <MarshalAs(UnmanagedType.Bool)> explicitString As String, <MarshalAs(UnmanagedType.Bool)> ByRef explicitByRefString As String, pString As String, ByRef pByRefString As String, pInt As Integer, ByRef pByRefInt As Integer ) As <MarshalAs(UnmanagedType.BStr)> Integer End Module ]]> </file> </compilation> Const bstr = &H13 Const bool = &H2 Const byvalstr = &H22 Const ansi_bstr = &H23 Dim blobs = New Dictionary(Of String, Byte())() From { {"Foo:", New Byte() {bstr}}, {"Foo:explicitInt", New Byte() {bstr}}, {"Foo:explicitByRefInt", New Byte() {bstr}}, {"Foo:explicitString", New Byte() {bool}}, {"Foo:explicitByRefString", New Byte() {bool}}, {"Foo:pString", New Byte() {byvalstr}}, {"Foo:pByRefString", New Byte() {ansi_bstr}}, {"Foo:pInt", Nothing}, {"Foo:pByRefInt", Nothing} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False, expectedSignatures:= { Signature("M", "Foo", ".method [System.Runtime.InteropServices.DllImportAttribute(""foo"", EntryPoint = ""Foo"", CharSet = 2, ExactSpelling = True, SetLastError = True, PreserveSig = True, CallingConvention = 1, BestFitMapping = False, ThrowOnUnmappableChar = False)] " & "[System.Runtime.InteropServices.PreserveSigAttribute()] " & "public static pinvokeimpl System.Int32 Foo(" & "System.Int32 explicitInt, " & "System.Int32& explicitByRefInt, " & "System.String explicitString, " & "System.String& explicitByRefString, " & "System.String& pString, " & "System.String& pByRefString, " & "System.Int32 pInt, " & "System.Int32& pByRefInt" & ") cil managed preservesig") }) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub Parameters_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Class X Public Shared Sub f1(<MarshalAs(UnmanagedType.ByValArray)> ByValArray As Integer, <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> ByValTStr As Integer) End Sub Public Shared Function f2() As <MarshalAs(UnmanagedType.ByValArray)> Integer Return 0 End Function Public Shared Function f3() As <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> Integer Return 0 End Function <MarshalAs(UnmanagedType.VBByRefStr)> Public field As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeNotValidForFields, "UnmanagedType.VBByRefStr").WithArguments("VBByRefStr")) End Sub ''' <summary> ''' type only, only on parameters ''' </summary> <Fact> Public Sub NativeTypeByValStr() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class X Shared Function f( <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> ByRef VBByRefStr_e1 As Integer, _ <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> VBByRefStr_e2 As Char(), _ <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> VBByRefStr_e3 As Integer) _ As <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Integer Return 0 End Function End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"f:", New Byte() {&H22}}, {"f:VBByRefStr_e1", New Byte() {&H22}}, {"f:VBByRefStr_e2", New Byte() {&H22}}, {"f:VBByRefStr_e3", New Byte() {&H22}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) 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 Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Roslyn.Utilities Imports Xunit Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_MarshalAs Inherits BasicTestBase #Region "Helpers" Private Sub VerifyFieldMetadataDecoding(verifier As CompilationVerifier, blobs As Dictionary(Of String, Byte())) Dim count = 0 Using assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData) Dim c = VisualBasicCompilation.Create("c", syntaxTrees:=New VisualBasicSyntaxTree() {}, references:={assembly.GetReference()}) For Each typeSym As NamedTypeSymbol In c.GlobalNamespace.GetMembers().Where(Function(s) s.Kind = SymbolKind.NamedType) Dim fields = typeSym.GetMembers().Where(Function(s) s.Kind = SymbolKind.Field) For Each field As FieldSymbol In fields Assert.Null(field.MarshallingInformation) Dim blob = blobs(field.Name) If blob IsNot Nothing AndAlso blob(0) <= &H50 Then Assert.Equal(CType(blob(0), UnmanagedType), field.MarshallingType) Else Assert.Equal(CType(0, UnmanagedType), field.MarshallingType) End If count = count + 1 Next Next End Using Assert.True(count > 0, "Expected at least one field") End Sub Private Sub VerifyParameterMetadataDecoding(verifier As CompilationVerifier, blobs As Dictionary(Of String, Byte())) Dim count = 0 Using assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData) Dim c = VisualBasicCompilation.Create("c", syntaxTrees:=New VisualBasicSyntaxTree() {}, references:={assembly.GetReference()}) For Each typeSym As NamedTypeSymbol In c.GlobalNamespace.GetMembers().Where(Function(s) s.Kind = SymbolKind.NamedType) Dim methods = typeSym.GetMembers().Where(Function(s) s.Kind = SymbolKind.Method) For Each method As MethodSymbol In methods For Each parameter In method.Parameters Assert.Null(parameter.MarshallingInformation) Dim blob = blobs(method.Name & ":" & parameter.Name) If blob IsNot Nothing AndAlso blob(0) <= &H50 Then Assert.Equal(CType(blob(0), UnmanagedType), parameter.MarshallingType) Else Assert.Equal(CType(0, UnmanagedType), parameter.MarshallingType) End If count = count + 1 Next Next Next End Using Assert.True(count > 0, "Expected at least one parameter") End Sub #End Region ''' <summary> ''' type only, others ignored, field type ignored ''' </summary> <Fact> Public Sub SimpleTypes() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(CShort(0))> Public ZeroShort As X <MarshalAs(DirectCast(0, UnmanagedType))> Public Zero As X <MarshalAs(DirectCast(&H1FFFFFFF, UnmanagedType))> Public MaxValue As X <MarshalAs(DirectCast((&H123456), UnmanagedType))> Public _0x123456 As X <MarshalAs(DirectCast((&H1000), UnmanagedType))> Public _0x1000 As X <MarshalAs(UnmanagedType.AnsiBStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public AnsiBStr As X <MarshalAs(UnmanagedType.AsAny, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public AsAny As Double <MarshalAs(UnmanagedType.Bool, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public Bool As X <MarshalAs(UnmanagedType.BStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public BStr As X <MarshalAs(UnmanagedType.Currency, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public Currency As Integer <MarshalAs(UnmanagedType.[Error], ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public [Error] As Integer <MarshalAs(UnmanagedType.FunctionPtr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public FunctionPtr As Integer <MarshalAs(UnmanagedType.I1, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I1 As Integer <MarshalAs(UnmanagedType.I2, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I2 As Integer <MarshalAs(UnmanagedType.I4, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I4 As Integer <MarshalAs(UnmanagedType.I8, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public I8 As Integer <MarshalAs(UnmanagedType.LPStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPStr As Integer <MarshalAs(UnmanagedType.LPStruct, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPStruct As Integer <MarshalAs(UnmanagedType.LPTStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPTStr As Integer <MarshalAs(UnmanagedType.LPWStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public LPWStr As Integer <MarshalAs(UnmanagedType.R4, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public R4 As Integer <MarshalAs(UnmanagedType.R8, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public R8 As Integer <MarshalAs(UnmanagedType.Struct, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public Struct As Integer <MarshalAs(UnmanagedType.SysInt, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public SysInt As Decimal <MarshalAs(UnmanagedType.SysUInt, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public SysUInt As Integer() <MarshalAs(UnmanagedType.TBStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public TBStr As Object() <MarshalAs(UnmanagedType.U1, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U1 As Integer <MarshalAs(UnmanagedType.U2, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U2 As Double <MarshalAs(UnmanagedType.U4, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U4 As Boolean <MarshalAs(UnmanagedType.U8, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public U8 As String <MarshalAs(UnmanagedType.VariantBool, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public VariantBool As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"ZeroShort", New Byte() {&H0}}, {"Zero", New Byte() {&H0}}, {"MaxValue", New Byte() {&HDF, &HFF, &HFF, &HFF}}, {"_0x1000", New Byte() {&H90, &H0}}, {"_0x123456", New Byte() {&HC0, &H12, &H34, &H56}}, {"AnsiBStr", New Byte() {&H23}}, {"AsAny", New Byte() {&H28}}, {"Bool", New Byte() {&H2}}, {"BStr", New Byte() {&H13}}, {"Currency", New Byte() {&HF}}, {"Error", New Byte() {&H2D}}, {"FunctionPtr", New Byte() {&H26}}, {"I1", New Byte() {&H3}}, {"I2", New Byte() {&H5}}, {"I4", New Byte() {&H7}}, {"I8", New Byte() {&H9}}, {"LPStr", New Byte() {&H14}}, {"LPStruct", New Byte() {&H2B}}, {"LPTStr", New Byte() {&H16}}, {"LPWStr", New Byte() {&H15}}, {"R4", New Byte() {&HB}}, {"R8", New Byte() {&HC}}, {"Struct", New Byte() {&H1B}}, {"SysInt", New Byte() {&H1F}}, {"SysUInt", New Byte() {&H20}}, {"TBStr", New Byte() {&H24}}, {"U1", New Byte() {&H4}}, {"U2", New Byte() {&H6}}, {"U4", New Byte() {&H8}}, {"U8", New Byte() {&HA}}, {"VariantBool", New Byte() {&H25}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub SimpleTypes_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Class X <MarshalAs(CType(-1, UnmanagedType))> Dim MinValue_1 As X <MarshalAs(CType(&H20000000, UnmanagedType))> Dim MaxValue_1 As X End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttribute1, "CType(-1, UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "CType(&H20000000, UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (type, IidParamIndex), others ignored, field type ignored ''' </summary> <Fact> Public Sub ComInterfaces() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.IDispatch, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=0, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public IDispatch As Byte <MarshalAs(UnmanagedType.[Interface], ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public [Interface] As X <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=2, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public IUnknown As X() <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H1FFFFFFF, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public MaxValue As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H123456, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public m_123456 As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H1000, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public m_0x1000 As X <MarshalAs(UnmanagedType.IDispatch)> Public [Default] As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"IDispatch", New Byte() {&H1A, &H0}}, {"Interface", New Byte() {&H1C, &H1}}, {"IUnknown", New Byte() {&H19, &H2}}, {"MaxValue", New Byte() {&H19, &HDF, &HFF, &HFF, &HFF}}, {"m_123456", New Byte() {&H19, &HC0, &H12, &H34, &H56}}, {"m_0x1000", New Byte() {&H19, &H90, &H0}}, {"Default", New Byte() {&H1A}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub ComInterfaces_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Class X <MarshalAs(UnmanagedType.IDispatch, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim IDispatch_MinValue_1 As Integer <MarshalAs(UnmanagedType.[Interface], ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim Interface_MinValue_1 As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim IUnknown_MinValue_1 As Integer <MarshalAs(UnmanagedType.IUnknown, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=&H20000000, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim IUnknown_MaxValue_1 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "IidParameterIndex:=&H20000000").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (ArraySubType, SizeConst, SizeParamIndex), SafeArraySubType not allowed, others ignored ''' </summary> <Fact> Public Sub NativeTypeArray() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.LPArray)> Public LPArray0 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public LPArray1 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=0, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public LPArray2 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=&H1FFFFFFF, SizeParamIndex:=Short.MaxValue, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public LPArray3 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(&H50, UnmanagedType))> Public LPArray4 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(&H1FFFFFFF, UnmanagedType))> Public LPArray5 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(0, UnmanagedType))> Public LPArray6 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"LPArray0", New Byte() {&H2A, &H50}}, {"LPArray1", New Byte() {&H2A, &H17}}, {"LPArray2", New Byte() {&H2A, &H17, &H0, &H0, &H0}}, {"LPArray3", New Byte() {&H2A, &H17, &HC0, &H0, &H7F, &HFF, &HDF, &HFF, &HFF, &HFF, &H1}}, {"LPArray4", New Byte() {&H2A, &H50}}, {"LPArray5", New Byte() {&H2A, &HDF, &HFF, &HFF, &HFF}}, {"LPArray6", New Byte() {&H2A, &H0}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeArray_ElementTypes() Dim source As StringBuilder = New StringBuilder(<text> Imports System Imports System.Runtime.InteropServices Class X </text>.Value) Dim expectedBlobs = New Dictionary(Of String, Byte())() For i = 0 To SByte.MaxValue If i <> DirectCast(UnmanagedType.CustomMarshaler, Integer) Then Dim fldName As String = String.Format("m_{0:X}", i) source.AppendLine(String.Format("<MarshalAs(UnmanagedType.LPArray, ArraySubType := CType(&H{0:X}, UnmanagedType))>Dim {1} As Integer", i, fldName)) expectedBlobs.Add(fldName, New Byte() {&H2A, CByte(i)}) End If Next source.AppendLine("End Class") CompileAndVerifyFieldMarshal(source.ToString(), expectedBlobs) End Sub <Fact()> Public Sub NativeTypeArray_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class X <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim LPArray_e0 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=-1)> Dim LPArray_e1 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=0, SizeParamIndex:=-1)> Dim LPArray_e2 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=Int32.MaxValue, SizeParamIndex:=Int16.MaxValue)> Dim LPArray_e3 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.U8, SizeConst:=Int32.MaxValue / 4 + 1, SizeParamIndex:=Int16.MaxValue)> Dim LPArray_e4 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.CustomMarshaler)> Dim LPArray_e5 As Integer <MarshalAs(UnmanagedType.LPArray, SafeArraySubType:=VarEnum.VT_I1)> Dim LPArray_e6 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast(&H20000000, UnmanagedType))> Dim LPArray_e7 As Integer <MarshalAs(UnmanagedType.LPArray, ArraySubType:=DirectCast((-1), UnmanagedType))> Dim LPArray_e8 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_BSTR"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeParamIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeParamIndex:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=Int32.MaxValue").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=Int32.MaxValue / 4 + 1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "ArraySubType:=UnmanagedType.CustomMarshaler").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_I1"), Diagnostic(ERRID.ERR_BadAttribute1, "ArraySubType:=DirectCast(&H20000000, UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "ArraySubType:=DirectCast((-1), UnmanagedType)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (ArraySubType, SizeConst), (SizeParamIndex, SafeArraySubType) not allowed, others ignored ''' </summary> <Fact> Public Sub NativeTypeFixedArray() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValArray)> Public ByValArray0 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public ByValArray1 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=0, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public ByValArray2 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=(Int32.MaxValue - 3) / 4, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=Nothing)> Public ByValArray3 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.AsAny)> Public ByValArray4 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.CustomMarshaler)> Public ByValArray5 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"ByValArray0", New Byte() {&H1E, &H1}}, {"ByValArray1", New Byte() {&H1E, &H1, &H17}}, {"ByValArray2", New Byte() {&H1E, &H0, &H17}}, {"ByValArray3", New Byte() {&H1E, &HDF, &HFF, &HFF, &HFF, &H17}}, {"ByValArray4", New Byte() {&H1E, &H1, &H28}}, {"ByValArray5", New Byte() {&H1E, &H1, &H2C}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeFixedArray_ElementTypes() Dim source As StringBuilder = New StringBuilder(<text> Imports System Imports System.Runtime.InteropServices Class X </text>.Value) Dim expectedBlobs = New Dictionary(Of String, Byte())() Dim i As Integer = 0 While i < SByte.MaxValue Dim fldName As String = String.Format("m_{0:X}", i) source.AppendLine(String.Format("<MarshalAs(UnmanagedType.ByValArray, ArraySubType := CType(&H{0:X}, UnmanagedType))>Dim {1} As Integer", i, fldName)) expectedBlobs.Add(fldName, New Byte() {&H1E, &H1, CByte(i)}) i = i + 1 End While source.AppendLine("End Class") CompileAndVerifyFieldMarshal(source.ToString(), expectedBlobs) End Sub <Fact()> Public Sub NativeTypeFixedArray_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim ByValArray_e1 As Integer <MarshalAs(UnmanagedType.ByValArray, SizeParamIndex:=Int16.MaxValue)> Dim ByValArray_e2 As Integer <MarshalAs(UnmanagedType.ByValArray, SafeArraySubType:=VarEnum.VT_I2)> Dim ByValArray_e3 As Integer <MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.ByValTStr, SizeConst:=&H20000000)> Dim ByValArray_e4 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_BSTR"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=-1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=Int16.MaxValue"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArraySubType:=VarEnum.VT_I2"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=&H20000000").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub ''' <summary> ''' (SafeArraySubType, SafeArrayUserDefinedSubType), (ArraySubType, SizeConst, SizeParamIndex) not allowed, ''' (SafeArraySubType, SafeArrayUserDefinedSubType) not allowed together unless VT_DISPATCH, VT_UNKNOWN, VT_RECORD; others ignored. ''' </summary> <Fact> Public Sub NativeTypeSafeArray() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.SafeArray)> Public SafeArray0 As Integer <MarshalAs(UnmanagedType.SafeArray, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR)> Public SafeArray1 As Integer <MarshalAs(UnmanagedType.SafeArray, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArrayUserDefinedSubType:=GetType(X))> Public SafeArray2 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=Nothing)> Public SafeArray3 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=GetType(Void))> Public SafeArray4 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_EMPTY)> Public SafeArray8 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(Integer()()))> Public SafeArray9 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(Nullable(Of)))> Public SafeArray10 As Integer End Class ]]> </file> </compilation> Dim aqn = Encoding.ASCII.GetBytes("System.Int32[][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") Dim openGenericAqn = Encoding.ASCII.GetBytes("System.Nullable`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") Dim blobs = New Dictionary(Of String, Byte()) From { {"SafeArray0", New Byte() {&H1D}}, {"SafeArray1", New Byte() {&H1D, &H8}}, {"SafeArray2", New Byte() {&H1D}}, {"SafeArray3", New Byte() {&H1D}}, {"SafeArray4", New Byte() {&H1D}}, {"SafeArray8", New Byte() {&H1D, &H0}}, {"SafeArray9", New Byte() {&H1D, &H24, CByte(aqn.Length)}.Append(aqn)}, {"SafeArray10", New Byte() {&H1D, &H24, CByte(openGenericAqn.Length)}.Append(openGenericAqn)} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub NativeTypeSafeArray_CCIOnly() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Public Class C(Of T) Public Class D(Of S) Public Class E End Class End Class End Class Public Class X <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(C(Of Integer).D(Of Boolean).E))> Public SafeArray11 As Integer End Class ]]> </file> </compilation> Dim nestedAqn = Encoding.ASCII.GetBytes("C`1+D`1+E[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") Dim blobs = New Dictionary(Of String, Byte()) From { {"SafeArray11", New Byte() {&H1D, &H24, &H80, &HC4}.Append(nestedAqn)} } ' RefEmit has slightly different encoding of the type name Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeSafeArray_RefEmitDiffers() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_DISPATCH, SafeArrayUserDefinedSubType:=GetType(List(Of X)()()))> Dim SafeArray5 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_UNKNOWN, SafeArrayUserDefinedSubType:=GetType(X))> Dim SafeArray6 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_RECORD, SafeArrayUserDefinedSubType:=GetType(X))> Dim SafeArray7 As Integer End Class ]]>.Value Dim e = Encoding.ASCII Dim cciBlobs = New Dictionary(Of String, Byte()) From { {"SafeArray5", New Byte() {&H1D, &H9, &H75}.Append(e.GetBytes("System.Collections.Generic.List`1[X][][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"))}, {"SafeArray6", New Byte() {&H1D, &HD, &H1, &H58}}, {"SafeArray7", New Byte() {&H1D, &H24, &H1, &H58}} } CompileAndVerifyFieldMarshal(source, cciBlobs) End Sub <Fact()> Public Sub NativeTypeSafeArray_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.SafeArray, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim SafeArray_e1 As Integer <MarshalAs(UnmanagedType.SafeArray, ArraySubType:=UnmanagedType.ByValTStr)> Dim SafeArray_e2 As Integer <MarshalAs(UnmanagedType.SafeArray, SizeConst:=1)> Dim SafeArray_e3 As Integer <MarshalAs(UnmanagedType.SafeArray, SizeParamIndex:=1)> Dim SafeArray_e4 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing)> Dim SafeArray_e5 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=Nothing, SafeArraySubType:=VarEnum.VT_BLOB)> Dim SafeArray_e6 As Integer <MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType:=GetType(Integer), SafeArraySubType:=0)> Dim SafeArray_e7 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeConst:=-1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=-1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=Nothing"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeConst:=1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=Nothing"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=Nothing"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType:=GetType(Integer)")) End Sub ''' <summary> ''' (SizeConst - required), (SizeParamIndex, ArraySubType) not allowed ''' </summary> <Fact> Public Sub NativeTypeFixedSysString() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> Public ByValTStr1 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=&H1FFFFFFF, SafeArrayUserDefinedSubType:=GetType(Integer), IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing)> Public ByValTStr2 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"ByValTStr1", New Byte() {&H17, &H1}}, {"ByValTStr2", New Byte() {&H17, &HDF, &HFF, &HFF, &HFF}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub NativeTypeFixedSysString_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class X <MarshalAs(UnmanagedType.ByValTStr, ArraySubType:=UnmanagedType.ByValTStr, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Dim ByValTStr_e1 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=-1)> Dim ByValTStr_e2 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=(Int32.MaxValue - 3) / 4 + 1)> Dim ByValTStr_e3 As Integer <MarshalAs(UnmanagedType.ByValTStr)> Dim ByValTStr_e4 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1, SizeParamIndex:=1)> Dim ByValTStr_e5 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1, ArraySubType:=UnmanagedType.ByValTStr)> Dim ByValTStr_e6 As Integer <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1, SafeArraySubType:=VarEnum.VT_BSTR)> Dim ByValTStr_e7 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=-1"), Diagnostic(ERRID.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=-1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), Diagnostic(ERRID.ERR_BadAttribute1, "SizeConst:=(Int32.MaxValue - 3) / 4 + 1").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "SizeParamIndex:=1"), Diagnostic(ERRID.ERR_ParameterNotValidForType, "ArraySubType:=UnmanagedType.ByValTStr")) End Sub ''' <summary> ''' Custom (MarshalType, MarshalTypeRef, MarshalCookie) one of {MarshalType, MarshalTypeRef} required, others ignored ''' </summary> <Fact> Public Sub CustomMarshal() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Public Class X <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=Nothing)> Public CustomMarshaler1 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=Nothing)> Public CustomMarshaler2 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="foo", MarshalTypeRef:=GetType(Integer))> Public CustomMarshaler3 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=ChrW(&H1234) & "f" & ChrW(0) & "oozzz")> Public CustomMarshaler4 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="f" & ChrW(0) & "oozzz")> Public CustomMarshaler5 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")> Public CustomMarshaler6 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Public CustomMarshaler7 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=GetType(Integer))> Public CustomMarshaler8 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=GetType(Integer), MarshalType:="foo", MarshalCookie:="hello" & ChrW(0) & "world(" & ChrW(&H1234) & ")")> Public CustomMarshaler9 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=Nothing, MarshalTypeRef:=GetType(Integer))> Public CustomMarshaler10 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="foo", MarshalTypeRef:=Nothing)> Public CustomMarshaler11 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=Nothing, MarshalTypeRef:=Nothing)> Public CustomMarshaler12 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="aaa" & ChrW(0) & "bbb", MarshalCookie:="ccc" & ChrW(0) & "ddd")> Public CustomMarshaler13 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:=ChrW(&HD869) & ChrW(&HDED6), MarshalCookie:=ChrW(&HD869) & ChrW(&HDED6))> Public CustomMarshaler14 As Integer End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"CustomMarshaler1", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler2", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler3", New Byte() {&H2C, &H0, &H0, &H3, &H66, &H6F, &H6F, &H0}}, {"CustomMarshaler4", New Byte() {&H2C, &H0, &H0, &HA, &HE1, &H88, &HB4, &H66, &H0, &H6F, &H6F, &H7A, &H7A, &H7A, &H0}}, {"CustomMarshaler5", New Byte() {&H2C, &H0, &H0, &H7, &H66, &H0, &H6F, &H6F, &H7A, &H7A, &H7A, &H0}}, {"CustomMarshaler6", New Byte() {&H2C, &H0, &H0, &H60}.Append(Encoding.UTF8.GetBytes("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" & ChrW(0)))}, {"CustomMarshaler7", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler8", New Byte() {&H2C, &H0, &H0, &H59}.Append(Encoding.UTF8.GetBytes("System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" & ChrW(0)))}, {"CustomMarshaler9", New Byte() {&H2C, &H0, &H0, &H3, &H66, &H6F, &H6F, &H10, &H68, &H65, &H6C, &H6C, &H6F, &H0, &H77, &H6F, &H72, &H6C, &H64, &H28, &HE1, &H88, &HB4, &H29}}, {"CustomMarshaler10", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler11", New Byte() {&H2C, &H0, &H0, &H3, &H66, &H6F, &H6F, &H0}}, {"CustomMarshaler12", New Byte() {&H2C, &H0, &H0, &H0, &H0}}, {"CustomMarshaler13", New Byte() {&H2C, &H0, &H0, &H7, &H61, &H61, &H61, &H0, &H62, &H62, &H62, &H7, &H63, &H63, &H63, &H0, &H64, &H64, &H64}}, {"CustomMarshaler14", New Byte() {&H2C, &H0, &H0, &H4, &HF0, &HAA, &H9B, &H96, &H4, &HF0, &HAA, &H9B, &H96}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs) VerifyFieldMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub CustomMarshal_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Public Class X <MarshalAs(UnmanagedType.CustomMarshaler)> Dim CustomMarshaler_e0 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="a" & ChrW(&HDC00) & "b", MarshalCookie:="b")> Dim CustomMarshaler_e1 As Integer <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="x", MarshalCookie:="y" & ChrW(&HDC00))> Dim CustomMarshaler_e2 As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_AttributeParameterRequired2, "MarshalAs").WithArguments("MarshalType", "MarshalTypeRef"), Diagnostic(ERRID.ERR_BadAttribute1, "MarshalType:=""a"" & ChrW(&HDC00) & ""b""").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute"), Diagnostic(ERRID.ERR_BadAttribute1, "MarshalCookie:=""y"" & ChrW(&HDC00)").WithArguments("System.Runtime.InteropServices.MarshalAsAttribute")) End Sub <Fact()> Public Sub Events_Error() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class C <MarshalAs(UnmanagedType.Bool)> Event e As Action End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "MarshalAs").WithArguments("MarshalAsAttribute", "e")) End Sub <Fact()> Public Sub MarshalAs_AllFieldTargets() Dim source = <compilation><file><![CDATA[ Imports System Imports System.Runtime.InteropServices Class Z <MarshalAs(UnmanagedType.Bool)> Dim f As Integer End Class Module M <MarshalAs(UnmanagedType.Bool)> Public WithEvents we As New Z End Module Enum En <MarshalAs(UnmanagedType.Bool)> A = 1 <MarshalAs(UnmanagedType.Bool)> B End Enum ]]></file></compilation> CompileAndVerifyFieldMarshal(source, Function(name, _omitted1) Return If(name = "f" Or name = "_we" Or name = "A" Or name = "B", New Byte() {&H2}, Nothing) End Function) End Sub <Fact()> Public Sub Parameters() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic.Strings Class X Public Shared Function foo(<MarshalAs(UnmanagedType.IDispatch)> ByRef IDispatch As Integer, <MarshalAs(UnmanagedType.LPArray)> ByRef LPArray0 As Integer, <MarshalAs(UnmanagedType.SafeArray, SafeArraySubType:=VarEnum.VT_EMPTY)> SafeArray8 As Integer, <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="aaa" & ChrW(0) & "bbb", MarshalCookie:="ccc" & ChrW(0) & "ddd")> CustomMarshaler13 As Integer) As <MarshalAs(UnmanagedType.LPStr)> X Return Nothing End Function End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {"foo:", New Byte() {&H14}}, {"foo:IDispatch", New Byte() {&H1A}}, {"foo:LPArray0", New Byte() {&H2A, &H50}}, {"foo:SafeArray8", New Byte() {&H1D, &H0}}, {"foo:CustomMarshaler13", New Byte() {&H2C, &H0, &H0, &H7, &H61, &H61, &H61, &H0, &H62, &H62, &H62, &H7, &H63, &H63, &H63, &H0, &H64, &H64, &H64}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Events() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module X Custom Event E As Action AddHandler(<MarshalAs(UnmanagedType.BStr)> eAdd As Action) End AddHandler RemoveHandler(<MarshalAs(UnmanagedType.BStr)> eRemove As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Module ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {"add_E:eAdd", New Byte() {&H13}}, {"remove_E:eRemove", New Byte() {&H13}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Properties() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module C Property P(<MarshalAs(UnmanagedType.I2)> pIndex As Integer) As <MarshalAs(UnmanagedType.I4)> Integer Get Return 0 End Get Set(<MarshalAs(UnmanagedType.I8)> pValue As Integer) End Set End Property Property Q As <MarshalAs(UnmanagedType.I4)> Integer Get Return 0 End Get Set(qValue As Integer) End Set End Property Property CRW As <MarshalAs(UnmanagedType.I4)> Integer WriteOnly Property CW As <MarshalAs(UnmanagedType.I4)> Integer Set(sValue As Integer) End Set End Property ReadOnly Property CR As <MarshalAs(UnmanagedType.I4)> Integer Get Return 0 End Get End Property End Module Interface I Property IRW As <MarshalAs(UnmanagedType.I4)> Integer ReadOnly Property IR As <MarshalAs(UnmanagedType.I4)> Integer WriteOnly Property IW As <MarshalAs(UnmanagedType.I4)> Integer Property IRW2(a As Integer, b As Integer) As <MarshalAs(UnmanagedType.I4)> Integer ReadOnly Property IR2(a As Integer, b As Integer) As <MarshalAs(UnmanagedType.I4)> Integer WriteOnly Property IW2(a As Integer, b As Integer) As <MarshalAs(UnmanagedType.I4)> Integer End Interface ]]> </file> </compilation> Dim i2 = New Byte() {&H5} Dim i4 = New Byte() {&H7} Dim i8 = New Byte() {&H9} ' Dev11 incorrectly applies return-type MarshalAs on the first parameter of an interface property. Dim blobs = New Dictionary(Of String, Byte())() From { {"get_P:", i4}, {"get_P:pIndex", i2}, {"set_P:pIndex", i2}, {"set_P:pValue", i8}, {"get_Q:", i4}, {"set_Q:qValue", Nothing}, {"get_CRW:", i4}, {"set_CRW:AutoPropertyValue", Nothing}, {"set_CW:sValue", Nothing}, {"get_CR:", i4}, {"get_IRW:", i4}, {"set_IRW:Value", i4}, {"get_IR:", i4}, {"set_IW:Value", i4}, {"get_IRW2:", i4}, {"get_IRW2:a", Nothing}, {"get_IRW2:b", Nothing}, {"set_IRW2:a", Nothing}, {"set_IRW2:b", Nothing}, {"set_IRW2:Value", i4}, {"get_IR2:", i4}, {"get_IR2:a", Nothing}, {"get_IR2:b", Nothing}, {"set_IW2:a", Nothing}, {"set_IW2:b", Nothing}, {"set_IW2:Value", i4} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) CompilationUtils.AssertTheseDiagnostics(verifier.Compilation, <errors><![CDATA[ BC42364: Attributes applied on a return type of a WriteOnly Property have no effect. WriteOnly Property CW As <MarshalAs(UnmanagedType.I4)> Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_PropertyReturnType_MissingAccessors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module C Property Q As <MarshalAs(UnmanagedType.I4)> Integer End Property End Module ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(c, <errors><![CDATA[ BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'. Property Q As <MarshalAs(UnmanagedType.I4)> Integer ~ ]]></errors>) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_PartialSubs() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Partial Class X Private Partial Sub F(<MarshalAs(UnmanagedType.BStr)> pf As Integer) End Sub Private Sub F(pf As Integer) End Sub Private Partial Sub G(pg As Integer) End Sub Private Sub G(<MarshalAs(UnmanagedType.BStr)> pg As Integer) End Sub Private Sub H(<MarshalAs(UnmanagedType.BStr)> ph As Integer) End Sub Private Partial Sub H(ph As Integer) End Sub Private Sub I(pi As Integer) End Sub Private Partial Sub I(<MarshalAs(UnmanagedType.BStr)> pi As Integer) End Sub End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {"F:pf", New Byte() {&H13}}, {"G:pg", New Byte() {&H13}}, {"H:ph", New Byte() {&H13}}, {"I:pi", New Byte() {&H13}} } CompileAndVerifyFieldMarshal(source, blobs, isField:=False) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Delegate() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Delegate Function D(<MarshalAs(UnmanagedType.BStr)>p As Integer, <MarshalAs(UnmanagedType.BStr)>ByRef q As Integer) As <MarshalAs(UnmanagedType.BStr)> Integer ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte())() From { {".ctor:TargetObject", Nothing}, {".ctor:TargetMethod", Nothing}, {"BeginInvoke:p", New Byte() {&H13}}, {"BeginInvoke:q", New Byte() {&H13}}, {"BeginInvoke:DelegateCallback", Nothing}, {"BeginInvoke:DelegateAsyncState", Nothing}, {"EndInvoke:p", New Byte() {&H13}}, {"EndInvoke:q", New Byte() {&H13}}, {"EndInvoke:DelegateAsyncResult", Nothing}, {"Invoke:", New Byte() {&H13}}, {"Invoke:p", New Byte() {&H13}}, {"Invoke:q", New Byte() {&H13}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact> Public Sub MarshalAs_AllParameterTargets_Declare() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Module M Declare Function Foo Lib "foo" ( <MarshalAs(UnmanagedType.BStr)> explicitInt As Integer, <MarshalAs(UnmanagedType.BStr)> ByRef explicitByRefInt As Integer, <MarshalAs(UnmanagedType.Bool)> explicitString As String, <MarshalAs(UnmanagedType.Bool)> ByRef explicitByRefString As String, pString As String, ByRef pByRefString As String, pInt As Integer, ByRef pByRefInt As Integer ) As <MarshalAs(UnmanagedType.BStr)> Integer End Module ]]> </file> </compilation> Const bstr = &H13 Const bool = &H2 Const byvalstr = &H22 Const ansi_bstr = &H23 Dim blobs = New Dictionary(Of String, Byte())() From { {"Foo:", New Byte() {bstr}}, {"Foo:explicitInt", New Byte() {bstr}}, {"Foo:explicitByRefInt", New Byte() {bstr}}, {"Foo:explicitString", New Byte() {bool}}, {"Foo:explicitByRefString", New Byte() {bool}}, {"Foo:pString", New Byte() {byvalstr}}, {"Foo:pByRefString", New Byte() {ansi_bstr}}, {"Foo:pInt", Nothing}, {"Foo:pByRefInt", Nothing} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False, expectedSignatures:= { Signature("M", "Foo", ".method [System.Runtime.InteropServices.DllImportAttribute(""foo"", EntryPoint = ""Foo"", CharSet = 2, ExactSpelling = True, SetLastError = True, PreserveSig = True, CallingConvention = 1, BestFitMapping = False, ThrowOnUnmappableChar = False)] " & "[System.Runtime.InteropServices.PreserveSigAttribute()] " & "public static pinvokeimpl System.Int32 Foo(" & "System.Int32 explicitInt, " & "System.Int32& explicitByRefInt, " & "System.String explicitString, " & "System.String& explicitByRefString, " & "System.String& pString, " & "System.String& pByRefString, " & "System.Int32 pInt, " & "System.Int32& pByRefInt" & ") cil managed preservesig") }) VerifyParameterMetadataDecoding(verifier, blobs) End Sub <Fact()> Public Sub Parameters_Errors() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Class X Public Shared Sub f1(<MarshalAs(UnmanagedType.ByValArray)> ByValArray As Integer, <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> ByValTStr As Integer) End Sub Public Shared Function f2() As <MarshalAs(UnmanagedType.ByValArray)> Integer Return 0 End Function Public Shared Function f3() As <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1)> Integer Return 0 End Function <MarshalAs(UnmanagedType.VBByRefStr)> Public field As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr"), Diagnostic(ERRID.ERR_MarshalUnmanagedTypeNotValidForFields, "UnmanagedType.VBByRefStr").WithArguments("VBByRefStr")) End Sub ''' <summary> ''' type only, only on parameters ''' </summary> <Fact> Public Sub NativeTypeByValStr() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class X Shared Function f( <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> ByRef VBByRefStr_e1 As Integer, _ <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> VBByRefStr_e2 As Char(), _ <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> VBByRefStr_e3 As Integer) _ As <MarshalAs(UnmanagedType.VBByRefStr, ArraySubType:=UnmanagedType.ByValTStr, IidParameterIndex:=-1, MarshalCookie:=Nothing, MarshalType:=Nothing, MarshalTypeRef:=Nothing, SafeArraySubType:=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType:=Nothing, SizeConst:=-1, SizeParamIndex:=-1)> Integer Return 0 End Function End Class ]]> </file> </compilation> Dim blobs = New Dictionary(Of String, Byte()) From { {"f:", New Byte() {&H22}}, {"f:VBByRefStr_e1", New Byte() {&H22}}, {"f:VBByRefStr_e2", New Byte() {&H22}}, {"f:VBByRefStr_e3", New Byte() {&H22}} } Dim verifier = CompileAndVerifyFieldMarshal(source, blobs, isField:=False) VerifyParameterMetadataDecoding(verifier, blobs) End Sub End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Core/Portable/CommandLine/AnalyzerConfig.SectionNameMatching.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.Diagnostics; using System.IO; using System.Text; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public sealed partial class AnalyzerConfig { internal readonly struct SectionNameMatcher { private readonly ImmutableArray<(int minValue, int maxValue)> _numberRangePairs; // internal for testing internal Regex Regex { get; } internal SectionNameMatcher( Regex regex, ImmutableArray<(int minValue, int maxValue)> numberRangePairs) { Debug.Assert(regex.GetGroupNumbers().Length - 1 == numberRangePairs.Length); Regex = regex; _numberRangePairs = numberRangePairs; } public bool IsMatch(string s) { if (_numberRangePairs.IsEmpty) { return Regex.IsMatch(s); } var match = Regex.Match(s); if (!match.Success) { return false; } Debug.Assert(match.Groups.Count - 1 == _numberRangePairs.Length); for (int i = 0; i < _numberRangePairs.Length; i++) { var (minValue, maxValue) = _numberRangePairs[i]; // Index 0 is the whole regex if (!int.TryParse(match.Groups[i + 1].Value, out int matchedNum) || matchedNum < minValue || matchedNum > maxValue) { return false; } } return true; } } /// <summary> /// Takes a <see cref="Section.Name"/> and creates a matcher that /// matches the given language. Returns null if the section name is /// invalid. /// </summary> internal static SectionNameMatcher? TryCreateSectionNameMatcher(string sectionName) { // An editorconfig section name is a language for recognizing file paths // defined by the following grammar: // // <path> ::= <path-list> // <path-list> ::= <path-item> | <path-item> <path-list> // <path-item> ::= "*" | "**" | "?" | <char> | <choice> | <range> // <char> ::= any unicode character // <choice> ::= "{" <choice-list> "}" // <choice-list> ::= <path-list> | <path-list> "," <choice-list> // <range> ::= "{" <integer> ".." <integer> "}" // <integer> ::= "-" <digit-list> | <digit-list> // <digit-list> ::= <digit> | <digit> <digit-list> // <digit> ::= 0-9 var sb = new StringBuilder(); sb.Append('^'); // EditorConfig matching depends on the whether or not there are // directory separators and where they are located in the section // name. Specifically, the editorconfig core parser says: // https://github.com/editorconfig/editorconfig-core-c/blob/5d3996811e962a717a7d7fdd0a941192382241a7/src/lib/editorconfig.c#L231 // // Pattern would be: // /dir/of/editorconfig/file[double_star]/[section] if section does not contain '/', // /dir/of/editorconfig/file[section] if section starts with a '/', or // /dir/of/editorconfig/file/[section] if section contains '/' but does not start with '/'. if (!sectionName.Contains("/")) { sb.Append(".*/"); } else if (sectionName[0] != '/') { sb.Append('/'); } var lexer = new SectionNameLexer(sectionName); var numberRangePairs = ArrayBuilder<(int minValue, int maxValue)>.GetInstance(); if (!TryCompilePathList(ref lexer, sb, parsingChoice: false, numberRangePairs)) { numberRangePairs.Free(); return null; } sb.Append('$'); return new SectionNameMatcher( new Regex(sb.ToString(), RegexOptions.Compiled), numberRangePairs.ToImmutableAndFree()); } internal static bool TryUnescapeSectionName(string sectionName, out string? escapedSectionName) { var sb = new StringBuilder(); SectionNameLexer lexer = new SectionNameLexer(sectionName); while (!lexer.IsDone) { var tokenKind = lexer.Lex(); if (tokenKind == TokenKind.SimpleCharacter) { sb.Append(lexer.EatCurrentCharacter()); } } escapedSectionName = sb.ToString(); return true; } /// <summary> /// Test if a section name is an absolute path with no special chars /// </summary> internal static bool IsAbsoluteEditorConfigPath(string sectionName) { // NOTE: editorconfig paths must use '/' as a directory separator character on all OS. // on all unix systems this is thus a simple test: does the path start with '/' // and contain no special chars? // on windows, a path can be either drive rooted or not (e.g. start with 'c:' or just '') // in addition to being absolute or relative. // for example c:myfile.cs is a relative path, but rooted on drive c: // /myfile2.cs is an absolute path but rooted to the current drive. // in addition there are UNC paths and volume guids (see https://docs.microsoft.com/en-us/dotnet/standard/io/file-path-formats) // but these start with \\ (and thus '/' in editor config terminology) // in this implementation we choose to ignore the drive root for the purposes of // determining validity. On windows c:/file.cs and /file.cs are both assumed to be // valid absolute paths, even though the second one is technically relative to // the current drive of the compiler working directory. // Note that this check has no impact on config correctness. Files on windows // will still be compared using their full path (including drive root) so it's // not possible to target the wrong file. It's just possible that the user won't // receive a warning that this section is ignored on windows in this edge case. SectionNameLexer nameLexer = new SectionNameLexer(sectionName); bool sawStartChar = false; int logicalIndex = 0; while (!nameLexer.IsDone) { if (nameLexer.Lex() != TokenKind.SimpleCharacter) { return false; } var simpleChar = nameLexer.EatCurrentCharacter(); // check the path starts with '/' if (logicalIndex == 0) { if (simpleChar == '/') { sawStartChar = true; } else if (Path.DirectorySeparatorChar == '/') { return false; } } // on windows we get a second chance to find the start char else if (!sawStartChar && Path.DirectorySeparatorChar == '\\') { if (logicalIndex == 1 && simpleChar != ':') { return false; } else if (logicalIndex == 2) { if (simpleChar != '/') { return false; } else { sawStartChar = true; } } } logicalIndex++; } return sawStartChar; } /// <summary> /// <![CDATA[ /// <path-list> ::= <path-item> | <path-item> <path-list> /// <path-item> ::= "*" | "**" | "?" | <char> | <choice> | <range> /// <char> ::= any unicode character /// <choice> ::= "{" <choice-list> "}" /// <choice-list> ::= <path-list> | <path-list> "," <choice-list> /// ]]> /// </summary> private static bool TryCompilePathList( ref SectionNameLexer lexer, StringBuilder sb, bool parsingChoice, ArrayBuilder<(int minValue, int maxValue)> numberRangePairs) { while (!lexer.IsDone) { var tokenKind = lexer.Lex(); switch (tokenKind) { case TokenKind.BadToken: // Parsing failure return false; case TokenKind.SimpleCharacter: // Matches just this character sb.Append(Regex.Escape(lexer.EatCurrentCharacter().ToString())); break; case TokenKind.Question: // '?' matches any single character sb.Append('.'); break; case TokenKind.Star: // Matches any string of characters except directory separator // Directory separator is defined in editorconfig spec as '/' sb.Append("[^/]*"); break; case TokenKind.StarStar: // Matches any string of characters sb.Append(".*"); break; case TokenKind.OpenCurly: // Back up token stream. The following helpers all expect a '{' lexer.Position--; // This is ambiguous between {num..num} and {item1,item2} // We need to look ahead to disambiguate. Looking for {num..num} // is easier because it can't be recursive. (string numStart, string numEnd)? rangeOpt = TryParseNumberRange(ref lexer); if (rangeOpt is null) { // Not a number range. Try a choice expression if (!TryCompileChoice(ref lexer, sb, numberRangePairs)) { return false; } // Keep looping. There may be more after the '}'. break; } else { (string numStart, string numEnd) = rangeOpt.GetValueOrDefault(); if (int.TryParse(numStart, out var intStart) && int.TryParse(numEnd, out var intEnd)) { var pair = intStart < intEnd ? (intStart, intEnd) : (intEnd, intStart); numberRangePairs.Add(pair); // Group allowing any digit sequence. The validity will be checked outside of the regex sb.Append("(-?[0-9]+)"); // Keep looping break; } return false; } case TokenKind.CloseCurly: // Either the end of a choice, or a failed parse return parsingChoice; case TokenKind.Comma: // The end of a choice section, or a failed parse return parsingChoice; case TokenKind.OpenBracket: sb.Append('['); if (!TryCompileCharacterClass(ref lexer, sb)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(tokenKind); } } // If we're parsing a choice we should not exit without a closing '}' return !parsingChoice; } /// <summary> /// Compile a globbing character class of the form [...]. Returns true if /// the character class was successfully compiled. False if there was a syntax /// error. The starting character is expected to be directly after the '['. /// </summary> private static bool TryCompileCharacterClass(ref SectionNameLexer lexer, StringBuilder sb) { // [...] should match any of the characters in the brackets, with special // behavior for four characters: '!' immediately after the opening bracket // implies the negation of the character class, '-' implies matching // between the locale-dependent range of the previous and next characters, // '\' escapes the following character, and ']' ends the range if (!lexer.IsDone && lexer.CurrentCharacter == '!') { sb.Append('^'); lexer.Position++; } while (!lexer.IsDone) { var currentChar = lexer.EatCurrentCharacter(); switch (currentChar) { case '-': // '-' means the same thing in regex as it does in the glob, so // put it in verbatim sb.Append(currentChar); break; case '\\': // Escape the next char if (lexer.IsDone) { return false; } sb.Append('\\'); sb.Append(lexer.EatCurrentCharacter()); break; case ']': sb.Append(currentChar); return true; default: sb.Append(Regex.Escape(currentChar.ToString())); break; } } // Stream ended without a closing bracket return false; } /// <summary> /// Parses choice defined by the following grammar: /// <![CDATA[ /// <choice> ::= "{" <choice-list> "}" /// <choice-list> ::= <path-list> | <path-list> "," <choice-list> /// ]]> /// </summary> private static bool TryCompileChoice( ref SectionNameLexer lexer, StringBuilder sb, ArrayBuilder<(int, int)> numberRangePairs) { if (lexer.Lex() != TokenKind.OpenCurly) { return false; } // Start a non-capturing group for the choice sb.Append("(?:"); // We start immediately after a '{' // Try to compile the nested <path-list> while (TryCompilePathList(ref lexer, sb, parsingChoice: true, numberRangePairs)) { // If we've successfully compiled a <path-list> the last token should // have been a ',' or a '}' char lastChar = lexer[lexer.Position - 1]; if (lastChar == ',') { // Another option sb.Append("|"); } else if (lastChar == '}') { // Close out the capture group sb.Append(")"); return true; } else { throw ExceptionUtilities.UnexpectedValue(lastChar); } } // Propagate failure return false; } /// <summary> /// Parses range defined by the following grammar. /// <![CDATA[ /// <range> ::= "{" <integer> ".." <integer> "}" /// <integer> ::= "-" <digit-list> | <digit-list> /// <digit-list> ::= <digit> | <digit> <digit-list> /// <digit> ::= 0-9 /// ]]> /// </summary> private static (string numStart, string numEnd)? TryParseNumberRange(ref SectionNameLexer lexer) { var saved = lexer.Position; if (lexer.Lex() != TokenKind.OpenCurly) { lexer.Position = saved; return null; } var numStart = lexer.TryLexNumber(); if (numStart is null) { // Not a number lexer.Position = saved; return null; } // The next two characters must be ".." if (!lexer.TryEatCurrentCharacter(out char c) || c != '.' || !lexer.TryEatCurrentCharacter(out c) || c != '.') { lexer.Position = saved; return null; } // Now another number var numEnd = lexer.TryLexNumber(); if (numEnd is null || lexer.IsDone || lexer.Lex() != TokenKind.CloseCurly) { // Not a number or no '}' lexer.Position = saved; return null; } return (numStart, numEnd); } private struct SectionNameLexer { private readonly string _sectionName; public int Position { get; set; } public SectionNameLexer(string sectionName) { _sectionName = sectionName; Position = 0; } public bool IsDone => Position >= _sectionName.Length; public TokenKind Lex() { int lexemeStart = Position; switch (_sectionName[Position]) { case '*': { int nextPos = Position + 1; if (nextPos < _sectionName.Length && _sectionName[nextPos] == '*') { Position += 2; return TokenKind.StarStar; } else { Position++; return TokenKind.Star; } } case '?': Position++; return TokenKind.Question; case '{': Position++; return TokenKind.OpenCurly; case ',': Position++; return TokenKind.Comma; case '}': Position++; return TokenKind.CloseCurly; case '[': Position++; return TokenKind.OpenBracket; case '\\': { // Backslash escapes the next character Position++; if (IsDone) { return TokenKind.BadToken; } return TokenKind.SimpleCharacter; } default: // Don't increment position, since caller needs to fetch the character return TokenKind.SimpleCharacter; } } public char CurrentCharacter => _sectionName[Position]; /// <summary> /// Call after getting <see cref="TokenKind.SimpleCharacter" /> from <see cref="Lex()" /> /// </summary> public char EatCurrentCharacter() => _sectionName[Position++]; /// <summary> /// Returns false if there are no more characters in the lex stream. /// Otherwise, produces the next character in the stream and returns true. /// </summary> public bool TryEatCurrentCharacter(out char nextChar) { if (IsDone) { nextChar = default; return false; } else { nextChar = EatCurrentCharacter(); return true; } } public char this[int position] => _sectionName[position]; /// <summary> /// Returns the string representation of a decimal integer, or null if /// the current lexeme is not an integer. /// </summary> public string? TryLexNumber() { bool start = true; var sb = new StringBuilder(); while (!IsDone) { char currentChar = CurrentCharacter; if (start && currentChar == '-') { Position++; sb.Append('-'); } else if (char.IsDigit(currentChar)) { Position++; sb.Append(currentChar); } else { break; } start = false; } var str = sb.ToString(); return str.Length == 0 || str == "-" ? null : str; } } private enum TokenKind { BadToken, SimpleCharacter, Star, StarStar, Question, OpenCurly, CloseCurly, Comma, DoubleDot, OpenBracket, } } }
// 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.Diagnostics; using System.IO; using System.Text; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public sealed partial class AnalyzerConfig { internal readonly struct SectionNameMatcher { private readonly ImmutableArray<(int minValue, int maxValue)> _numberRangePairs; // internal for testing internal Regex Regex { get; } internal SectionNameMatcher( Regex regex, ImmutableArray<(int minValue, int maxValue)> numberRangePairs) { Debug.Assert(regex.GetGroupNumbers().Length - 1 == numberRangePairs.Length); Regex = regex; _numberRangePairs = numberRangePairs; } public bool IsMatch(string s) { if (_numberRangePairs.IsEmpty) { return Regex.IsMatch(s); } var match = Regex.Match(s); if (!match.Success) { return false; } Debug.Assert(match.Groups.Count - 1 == _numberRangePairs.Length); for (int i = 0; i < _numberRangePairs.Length; i++) { var (minValue, maxValue) = _numberRangePairs[i]; // Index 0 is the whole regex if (!int.TryParse(match.Groups[i + 1].Value, out int matchedNum) || matchedNum < minValue || matchedNum > maxValue) { return false; } } return true; } } /// <summary> /// Takes a <see cref="Section.Name"/> and creates a matcher that /// matches the given language. Returns null if the section name is /// invalid. /// </summary> internal static SectionNameMatcher? TryCreateSectionNameMatcher(string sectionName) { // An editorconfig section name is a language for recognizing file paths // defined by the following grammar: // // <path> ::= <path-list> // <path-list> ::= <path-item> | <path-item> <path-list> // <path-item> ::= "*" | "**" | "?" | <char> | <choice> | <range> // <char> ::= any unicode character // <choice> ::= "{" <choice-list> "}" // <choice-list> ::= <path-list> | <path-list> "," <choice-list> // <range> ::= "{" <integer> ".." <integer> "}" // <integer> ::= "-" <digit-list> | <digit-list> // <digit-list> ::= <digit> | <digit> <digit-list> // <digit> ::= 0-9 var sb = new StringBuilder(); sb.Append('^'); // EditorConfig matching depends on the whether or not there are // directory separators and where they are located in the section // name. Specifically, the editorconfig core parser says: // https://github.com/editorconfig/editorconfig-core-c/blob/5d3996811e962a717a7d7fdd0a941192382241a7/src/lib/editorconfig.c#L231 // // Pattern would be: // /dir/of/editorconfig/file[double_star]/[section] if section does not contain '/', // /dir/of/editorconfig/file[section] if section starts with a '/', or // /dir/of/editorconfig/file/[section] if section contains '/' but does not start with '/'. if (!sectionName.Contains("/")) { sb.Append(".*/"); } else if (sectionName[0] != '/') { sb.Append('/'); } var lexer = new SectionNameLexer(sectionName); var numberRangePairs = ArrayBuilder<(int minValue, int maxValue)>.GetInstance(); if (!TryCompilePathList(ref lexer, sb, parsingChoice: false, numberRangePairs)) { numberRangePairs.Free(); return null; } sb.Append('$'); return new SectionNameMatcher( new Regex(sb.ToString(), RegexOptions.Compiled), numberRangePairs.ToImmutableAndFree()); } internal static bool TryUnescapeSectionName(string sectionName, out string? escapedSectionName) { var sb = new StringBuilder(); SectionNameLexer lexer = new SectionNameLexer(sectionName); while (!lexer.IsDone) { var tokenKind = lexer.Lex(); if (tokenKind == TokenKind.SimpleCharacter) { sb.Append(lexer.EatCurrentCharacter()); } } escapedSectionName = sb.ToString(); return true; } /// <summary> /// Test if a section name is an absolute path with no special chars /// </summary> internal static bool IsAbsoluteEditorConfigPath(string sectionName) { // NOTE: editorconfig paths must use '/' as a directory separator character on all OS. // on all unix systems this is thus a simple test: does the path start with '/' // and contain no special chars? // on windows, a path can be either drive rooted or not (e.g. start with 'c:' or just '') // in addition to being absolute or relative. // for example c:myfile.cs is a relative path, but rooted on drive c: // /myfile2.cs is an absolute path but rooted to the current drive. // in addition there are UNC paths and volume guids (see https://docs.microsoft.com/en-us/dotnet/standard/io/file-path-formats) // but these start with \\ (and thus '/' in editor config terminology) // in this implementation we choose to ignore the drive root for the purposes of // determining validity. On windows c:/file.cs and /file.cs are both assumed to be // valid absolute paths, even though the second one is technically relative to // the current drive of the compiler working directory. // Note that this check has no impact on config correctness. Files on windows // will still be compared using their full path (including drive root) so it's // not possible to target the wrong file. It's just possible that the user won't // receive a warning that this section is ignored on windows in this edge case. SectionNameLexer nameLexer = new SectionNameLexer(sectionName); bool sawStartChar = false; int logicalIndex = 0; while (!nameLexer.IsDone) { if (nameLexer.Lex() != TokenKind.SimpleCharacter) { return false; } var simpleChar = nameLexer.EatCurrentCharacter(); // check the path starts with '/' if (logicalIndex == 0) { if (simpleChar == '/') { sawStartChar = true; } else if (Path.DirectorySeparatorChar == '/') { return false; } } // on windows we get a second chance to find the start char else if (!sawStartChar && Path.DirectorySeparatorChar == '\\') { if (logicalIndex == 1 && simpleChar != ':') { return false; } else if (logicalIndex == 2) { if (simpleChar != '/') { return false; } else { sawStartChar = true; } } } logicalIndex++; } return sawStartChar; } /// <summary> /// <![CDATA[ /// <path-list> ::= <path-item> | <path-item> <path-list> /// <path-item> ::= "*" | "**" | "?" | <char> | <choice> | <range> /// <char> ::= any unicode character /// <choice> ::= "{" <choice-list> "}" /// <choice-list> ::= <path-list> | <path-list> "," <choice-list> /// ]]> /// </summary> private static bool TryCompilePathList( ref SectionNameLexer lexer, StringBuilder sb, bool parsingChoice, ArrayBuilder<(int minValue, int maxValue)> numberRangePairs) { while (!lexer.IsDone) { var tokenKind = lexer.Lex(); switch (tokenKind) { case TokenKind.BadToken: // Parsing failure return false; case TokenKind.SimpleCharacter: // Matches just this character sb.Append(Regex.Escape(lexer.EatCurrentCharacter().ToString())); break; case TokenKind.Question: // '?' matches any single character sb.Append('.'); break; case TokenKind.Star: // Matches any string of characters except directory separator // Directory separator is defined in editorconfig spec as '/' sb.Append("[^/]*"); break; case TokenKind.StarStar: // Matches any string of characters sb.Append(".*"); break; case TokenKind.OpenCurly: // Back up token stream. The following helpers all expect a '{' lexer.Position--; // This is ambiguous between {num..num} and {item1,item2} // We need to look ahead to disambiguate. Looking for {num..num} // is easier because it can't be recursive. (string numStart, string numEnd)? rangeOpt = TryParseNumberRange(ref lexer); if (rangeOpt is null) { // Not a number range. Try a choice expression if (!TryCompileChoice(ref lexer, sb, numberRangePairs)) { return false; } // Keep looping. There may be more after the '}'. break; } else { (string numStart, string numEnd) = rangeOpt.GetValueOrDefault(); if (int.TryParse(numStart, out var intStart) && int.TryParse(numEnd, out var intEnd)) { var pair = intStart < intEnd ? (intStart, intEnd) : (intEnd, intStart); numberRangePairs.Add(pair); // Group allowing any digit sequence. The validity will be checked outside of the regex sb.Append("(-?[0-9]+)"); // Keep looping break; } return false; } case TokenKind.CloseCurly: // Either the end of a choice, or a failed parse return parsingChoice; case TokenKind.Comma: // The end of a choice section, or a failed parse return parsingChoice; case TokenKind.OpenBracket: sb.Append('['); if (!TryCompileCharacterClass(ref lexer, sb)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(tokenKind); } } // If we're parsing a choice we should not exit without a closing '}' return !parsingChoice; } /// <summary> /// Compile a globbing character class of the form [...]. Returns true if /// the character class was successfully compiled. False if there was a syntax /// error. The starting character is expected to be directly after the '['. /// </summary> private static bool TryCompileCharacterClass(ref SectionNameLexer lexer, StringBuilder sb) { // [...] should match any of the characters in the brackets, with special // behavior for four characters: '!' immediately after the opening bracket // implies the negation of the character class, '-' implies matching // between the locale-dependent range of the previous and next characters, // '\' escapes the following character, and ']' ends the range if (!lexer.IsDone && lexer.CurrentCharacter == '!') { sb.Append('^'); lexer.Position++; } while (!lexer.IsDone) { var currentChar = lexer.EatCurrentCharacter(); switch (currentChar) { case '-': // '-' means the same thing in regex as it does in the glob, so // put it in verbatim sb.Append(currentChar); break; case '\\': // Escape the next char if (lexer.IsDone) { return false; } sb.Append('\\'); sb.Append(lexer.EatCurrentCharacter()); break; case ']': sb.Append(currentChar); return true; default: sb.Append(Regex.Escape(currentChar.ToString())); break; } } // Stream ended without a closing bracket return false; } /// <summary> /// Parses choice defined by the following grammar: /// <![CDATA[ /// <choice> ::= "{" <choice-list> "}" /// <choice-list> ::= <path-list> | <path-list> "," <choice-list> /// ]]> /// </summary> private static bool TryCompileChoice( ref SectionNameLexer lexer, StringBuilder sb, ArrayBuilder<(int, int)> numberRangePairs) { if (lexer.Lex() != TokenKind.OpenCurly) { return false; } // Start a non-capturing group for the choice sb.Append("(?:"); // We start immediately after a '{' // Try to compile the nested <path-list> while (TryCompilePathList(ref lexer, sb, parsingChoice: true, numberRangePairs)) { // If we've successfully compiled a <path-list> the last token should // have been a ',' or a '}' char lastChar = lexer[lexer.Position - 1]; if (lastChar == ',') { // Another option sb.Append("|"); } else if (lastChar == '}') { // Close out the capture group sb.Append(")"); return true; } else { throw ExceptionUtilities.UnexpectedValue(lastChar); } } // Propagate failure return false; } /// <summary> /// Parses range defined by the following grammar. /// <![CDATA[ /// <range> ::= "{" <integer> ".." <integer> "}" /// <integer> ::= "-" <digit-list> | <digit-list> /// <digit-list> ::= <digit> | <digit> <digit-list> /// <digit> ::= 0-9 /// ]]> /// </summary> private static (string numStart, string numEnd)? TryParseNumberRange(ref SectionNameLexer lexer) { var saved = lexer.Position; if (lexer.Lex() != TokenKind.OpenCurly) { lexer.Position = saved; return null; } var numStart = lexer.TryLexNumber(); if (numStart is null) { // Not a number lexer.Position = saved; return null; } // The next two characters must be ".." if (!lexer.TryEatCurrentCharacter(out char c) || c != '.' || !lexer.TryEatCurrentCharacter(out c) || c != '.') { lexer.Position = saved; return null; } // Now another number var numEnd = lexer.TryLexNumber(); if (numEnd is null || lexer.IsDone || lexer.Lex() != TokenKind.CloseCurly) { // Not a number or no '}' lexer.Position = saved; return null; } return (numStart, numEnd); } private struct SectionNameLexer { private readonly string _sectionName; public int Position { get; set; } public SectionNameLexer(string sectionName) { _sectionName = sectionName; Position = 0; } public bool IsDone => Position >= _sectionName.Length; public TokenKind Lex() { int lexemeStart = Position; switch (_sectionName[Position]) { case '*': { int nextPos = Position + 1; if (nextPos < _sectionName.Length && _sectionName[nextPos] == '*') { Position += 2; return TokenKind.StarStar; } else { Position++; return TokenKind.Star; } } case '?': Position++; return TokenKind.Question; case '{': Position++; return TokenKind.OpenCurly; case ',': Position++; return TokenKind.Comma; case '}': Position++; return TokenKind.CloseCurly; case '[': Position++; return TokenKind.OpenBracket; case '\\': { // Backslash escapes the next character Position++; if (IsDone) { return TokenKind.BadToken; } return TokenKind.SimpleCharacter; } default: // Don't increment position, since caller needs to fetch the character return TokenKind.SimpleCharacter; } } public char CurrentCharacter => _sectionName[Position]; /// <summary> /// Call after getting <see cref="TokenKind.SimpleCharacter" /> from <see cref="Lex()" /> /// </summary> public char EatCurrentCharacter() => _sectionName[Position++]; /// <summary> /// Returns false if there are no more characters in the lex stream. /// Otherwise, produces the next character in the stream and returns true. /// </summary> public bool TryEatCurrentCharacter(out char nextChar) { if (IsDone) { nextChar = default; return false; } else { nextChar = EatCurrentCharacter(); return true; } } public char this[int position] => _sectionName[position]; /// <summary> /// Returns the string representation of a decimal integer, or null if /// the current lexeme is not an integer. /// </summary> public string? TryLexNumber() { bool start = true; var sb = new StringBuilder(); while (!IsDone) { char currentChar = CurrentCharacter; if (start && currentChar == '-') { Position++; sb.Append('-'); } else if (char.IsDigit(currentChar)) { Position++; sb.Append(currentChar); } else { break; } start = false; } var str = sb.ToString(); return str.Length == 0 || str == "-" ? null : str; } } private enum TokenKind { BadToken, SimpleCharacter, Star, StarStar, Question, OpenCurly, CloseCurly, Comma, DoubleDot, OpenBracket, } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Workspaces/Core/Portable/Workspace/Solution/ProjectState_Checksum.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 Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class ProjectState { public bool TryGetStateChecksums(out ProjectStateChecksums stateChecksums) => _lazyChecksums.TryGetValue(out stateChecksums); public Task<ProjectStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken) => _lazyChecksums.GetValueAsync(cancellationToken); public async Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken) { var collection = await _lazyChecksums.GetValueAsync(cancellationToken).ConfigureAwait(false); return collection.Checksum; } public Checksum GetParseOptionsChecksum() => GetParseOptionsChecksum(_solutionServices.Workspace.Services.GetService<ISerializerService>()); private Checksum GetParseOptionsChecksum(ISerializerService serializer) => this.SupportsCompilation ? ChecksumCache.GetOrCreate(this.ParseOptions, _ => serializer.CreateParseOptionsChecksum(this.ParseOptions)) : Checksum.Null; private async Task<ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken)) { var documentChecksumsTasks = DocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken); var additionalDocumentChecksumTasks = AdditionalDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken); var analyzerConfigDocumentChecksumTasks = AnalyzerConfigDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken); var serializer = _solutionServices.Workspace.Services.GetService<ISerializerService>(); var infoChecksum = serializer.CreateChecksum(ProjectInfo.Attributes, cancellationToken); // these compiler objects doesn't have good place to cache checksum. but rarely ever get changed. var compilationOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(CompilationOptions, _ => serializer.CreateChecksum(CompilationOptions, cancellationToken)) : Checksum.Null; cancellationToken.ThrowIfCancellationRequested(); var parseOptionsChecksum = GetParseOptionsChecksum(serializer); var projectReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(ProjectReferences, _ => new ChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var metadataReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(MetadataReferences, _ => new ChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var analyzerReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(AnalyzerReferences, _ => new ChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false); var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false); var analyzerConfigDocumentChecksums = await Task.WhenAll(analyzerConfigDocumentChecksumTasks).ConfigureAwait(false); return new ProjectStateChecksums( infoChecksum, compilationOptionsChecksum, parseOptionsChecksum, documentChecksums: new ChecksumCollection(documentChecksums), projectReferenceChecksums, metadataReferenceChecksums, analyzerReferenceChecksums, additionalDocumentChecksums: new ChecksumCollection(additionalChecksums), analyzerConfigDocumentChecksumCollection: new ChecksumCollection(analyzerConfigDocumentChecksums)); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw 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; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class ProjectState { public bool TryGetStateChecksums(out ProjectStateChecksums stateChecksums) => _lazyChecksums.TryGetValue(out stateChecksums); public Task<ProjectStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken) => _lazyChecksums.GetValueAsync(cancellationToken); public async Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken) { var collection = await _lazyChecksums.GetValueAsync(cancellationToken).ConfigureAwait(false); return collection.Checksum; } public Checksum GetParseOptionsChecksum() => GetParseOptionsChecksum(_solutionServices.Workspace.Services.GetService<ISerializerService>()); private Checksum GetParseOptionsChecksum(ISerializerService serializer) => this.SupportsCompilation ? ChecksumCache.GetOrCreate(this.ParseOptions, _ => serializer.CreateParseOptionsChecksum(this.ParseOptions)) : Checksum.Null; private async Task<ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken)) { var documentChecksumsTasks = DocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken); var additionalDocumentChecksumTasks = AdditionalDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken); var analyzerConfigDocumentChecksumTasks = AnalyzerConfigDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken); var serializer = _solutionServices.Workspace.Services.GetService<ISerializerService>(); var infoChecksum = serializer.CreateChecksum(ProjectInfo.Attributes, cancellationToken); // these compiler objects doesn't have good place to cache checksum. but rarely ever get changed. var compilationOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(CompilationOptions, _ => serializer.CreateChecksum(CompilationOptions, cancellationToken)) : Checksum.Null; cancellationToken.ThrowIfCancellationRequested(); var parseOptionsChecksum = GetParseOptionsChecksum(serializer); var projectReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(ProjectReferences, _ => new ChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var metadataReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(MetadataReferences, _ => new ChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var analyzerReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(AnalyzerReferences, _ => new ChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false); var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false); var analyzerConfigDocumentChecksums = await Task.WhenAll(analyzerConfigDocumentChecksumTasks).ConfigureAwait(false); return new ProjectStateChecksums( infoChecksum, compilationOptionsChecksum, parseOptionsChecksum, documentChecksums: new ChecksumCollection(documentChecksums), projectReferenceChecksums, metadataReferenceChecksums, analyzerReferenceChecksums, additionalDocumentChecksums: new ChecksumCollection(additionalChecksums), analyzerConfigDocumentChecksumCollection: new ChecksumCollection(analyzerConfigDocumentChecksums)); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisState.SyntaxReferenceAnalyzerStateData.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.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal partial class AnalysisState { /// <summary> /// Stores the partial analysis state for a specific symbol declaration for a specific analyzer. /// </summary> internal sealed class DeclarationAnalyzerStateData : SyntaxNodeAnalyzerStateData { /// <summary> /// Partial analysis state for code block actions executed on the declaration. /// </summary> public CodeBlockAnalyzerStateData CodeBlockAnalysisState { get; } /// <summary> /// Partial analysis state for operation block actions executed on the declaration. /// </summary> public OperationBlockAnalyzerStateData OperationBlockAnalysisState { get; } public static new readonly DeclarationAnalyzerStateData FullyProcessedInstance = CreateFullyProcessedInstance(); public DeclarationAnalyzerStateData() { CodeBlockAnalysisState = new CodeBlockAnalyzerStateData(); OperationBlockAnalysisState = new OperationBlockAnalyzerStateData(); } private static DeclarationAnalyzerStateData CreateFullyProcessedInstance() { var instance = new DeclarationAnalyzerStateData(); instance.SetStateKind(StateKind.FullyProcessed); return instance; } public override void SetStateKind(StateKind stateKind) { CodeBlockAnalysisState.SetStateKind(stateKind); OperationBlockAnalysisState.SetStateKind(stateKind); base.SetStateKind(stateKind); } public override void Free() { base.Free(); CodeBlockAnalysisState.Free(); OperationBlockAnalysisState.Free(); } } /// <summary> /// Stores the partial analysis state for syntax node actions executed on the declaration. /// </summary> internal class SyntaxNodeAnalyzerStateData : AnalyzerStateData { public HashSet<SyntaxNode> ProcessedNodes { get; } public SyntaxNode CurrentNode { get; set; } public SyntaxNodeAnalyzerStateData() { CurrentNode = null; ProcessedNodes = new HashSet<SyntaxNode>(); } public void ClearNodeAnalysisState() { CurrentNode = null; ProcessedActions.Clear(); } public override void Free() { base.Free(); CurrentNode = null; ProcessedNodes.Clear(); } } /// <summary> /// Stores the partial analysis state for operation actions executed on the declaration. /// </summary> internal class OperationAnalyzerStateData : AnalyzerStateData { public HashSet<IOperation> ProcessedOperations { get; } public IOperation CurrentOperation { get; set; } public OperationAnalyzerStateData() { CurrentOperation = null; ProcessedOperations = new HashSet<IOperation>(); } public void ClearNodeAnalysisState() { CurrentOperation = null; ProcessedActions.Clear(); } public override void Free() { base.Free(); CurrentOperation = null; ProcessedOperations.Clear(); } } /// <summary> /// Stores the partial analysis state for code block actions or operation block actions executed on the declaration. /// </summary> internal abstract class BlockAnalyzerStateData<TBlockAction, TNodeStateData> : AnalyzerStateData where TBlockAction : AnalyzerAction where TNodeStateData : AnalyzerStateData, new() { public TNodeStateData ExecutableNodesAnalysisState { get; } public ImmutableHashSet<TBlockAction> CurrentBlockEndActions { get; set; } public ImmutableHashSet<AnalyzerAction> CurrentBlockNodeActions { get; set; } public BlockAnalyzerStateData() { ExecutableNodesAnalysisState = new TNodeStateData(); CurrentBlockEndActions = null; CurrentBlockNodeActions = null; } public override void SetStateKind(StateKind stateKind) { ExecutableNodesAnalysisState.SetStateKind(stateKind); base.SetStateKind(stateKind); } public override void Free() { base.Free(); ExecutableNodesAnalysisState.Free(); CurrentBlockEndActions = null; CurrentBlockNodeActions = null; } } /// <summary> /// Stores the partial analysis state for code block actions executed on the declaration. /// </summary> internal sealed class CodeBlockAnalyzerStateData : BlockAnalyzerStateData<CodeBlockAnalyzerAction, SyntaxNodeAnalyzerStateData> { } /// <summary> /// Stores the partial analysis state for operation block actions executed on the declaration. /// </summary> internal sealed class OperationBlockAnalyzerStateData : BlockAnalyzerStateData<OperationBlockAnalyzerAction, OperationAnalyzerStateData> { } } }
// 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.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal partial class AnalysisState { /// <summary> /// Stores the partial analysis state for a specific symbol declaration for a specific analyzer. /// </summary> internal sealed class DeclarationAnalyzerStateData : SyntaxNodeAnalyzerStateData { /// <summary> /// Partial analysis state for code block actions executed on the declaration. /// </summary> public CodeBlockAnalyzerStateData CodeBlockAnalysisState { get; } /// <summary> /// Partial analysis state for operation block actions executed on the declaration. /// </summary> public OperationBlockAnalyzerStateData OperationBlockAnalysisState { get; } public static new readonly DeclarationAnalyzerStateData FullyProcessedInstance = CreateFullyProcessedInstance(); public DeclarationAnalyzerStateData() { CodeBlockAnalysisState = new CodeBlockAnalyzerStateData(); OperationBlockAnalysisState = new OperationBlockAnalyzerStateData(); } private static DeclarationAnalyzerStateData CreateFullyProcessedInstance() { var instance = new DeclarationAnalyzerStateData(); instance.SetStateKind(StateKind.FullyProcessed); return instance; } public override void SetStateKind(StateKind stateKind) { CodeBlockAnalysisState.SetStateKind(stateKind); OperationBlockAnalysisState.SetStateKind(stateKind); base.SetStateKind(stateKind); } public override void Free() { base.Free(); CodeBlockAnalysisState.Free(); OperationBlockAnalysisState.Free(); } } /// <summary> /// Stores the partial analysis state for syntax node actions executed on the declaration. /// </summary> internal class SyntaxNodeAnalyzerStateData : AnalyzerStateData { public HashSet<SyntaxNode> ProcessedNodes { get; } public SyntaxNode CurrentNode { get; set; } public SyntaxNodeAnalyzerStateData() { CurrentNode = null; ProcessedNodes = new HashSet<SyntaxNode>(); } public void ClearNodeAnalysisState() { CurrentNode = null; ProcessedActions.Clear(); } public override void Free() { base.Free(); CurrentNode = null; ProcessedNodes.Clear(); } } /// <summary> /// Stores the partial analysis state for operation actions executed on the declaration. /// </summary> internal class OperationAnalyzerStateData : AnalyzerStateData { public HashSet<IOperation> ProcessedOperations { get; } public IOperation CurrentOperation { get; set; } public OperationAnalyzerStateData() { CurrentOperation = null; ProcessedOperations = new HashSet<IOperation>(); } public void ClearNodeAnalysisState() { CurrentOperation = null; ProcessedActions.Clear(); } public override void Free() { base.Free(); CurrentOperation = null; ProcessedOperations.Clear(); } } /// <summary> /// Stores the partial analysis state for code block actions or operation block actions executed on the declaration. /// </summary> internal abstract class BlockAnalyzerStateData<TBlockAction, TNodeStateData> : AnalyzerStateData where TBlockAction : AnalyzerAction where TNodeStateData : AnalyzerStateData, new() { public TNodeStateData ExecutableNodesAnalysisState { get; } public ImmutableHashSet<TBlockAction> CurrentBlockEndActions { get; set; } public ImmutableHashSet<AnalyzerAction> CurrentBlockNodeActions { get; set; } public BlockAnalyzerStateData() { ExecutableNodesAnalysisState = new TNodeStateData(); CurrentBlockEndActions = null; CurrentBlockNodeActions = null; } public override void SetStateKind(StateKind stateKind) { ExecutableNodesAnalysisState.SetStateKind(stateKind); base.SetStateKind(stateKind); } public override void Free() { base.Free(); ExecutableNodesAnalysisState.Free(); CurrentBlockEndActions = null; CurrentBlockNodeActions = null; } } /// <summary> /// Stores the partial analysis state for code block actions executed on the declaration. /// </summary> internal sealed class CodeBlockAnalyzerStateData : BlockAnalyzerStateData<CodeBlockAnalyzerAction, SyntaxNodeAnalyzerStateData> { } /// <summary> /// Stores the partial analysis state for operation block actions executed on the declaration. /// </summary> internal sealed class OperationBlockAnalyzerStateData : BlockAnalyzerStateData<OperationBlockAnalyzerAction, OperationAnalyzerStateData> { } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAddMissingReference.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 System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpAddMissingReference : AbstractEditorTest { private const string FileInLibraryProject1 = @"Public Class Class1 Inherits System.Windows.Forms.Form Public Sub goo() End Sub End Class Public Class class2 Public Sub goo(ByVal x As System.Windows.Forms.Form) End Sub Public Event ee As System.Windows.Forms.ColumnClickEventHandler End Class Public Class class3 Implements System.Windows.Forms.IButtonControl Public Property DialogResult() As System.Windows.Forms.DialogResult Implements System.Windows.Forms.IButtonControl.DialogResult Get End Get Set(ByVal Value As System.Windows.Forms.DialogResult) End Set End Property Public Sub NotifyDefault(ByVal value As Boolean) Implements System.Windows.Forms.IButtonControl.NotifyDefault End Sub Public Sub PerformClick() Implements System.Windows.Forms.IButtonControl.PerformClick End Sub End Class "; private const string FileInLibraryProject2 = @"Public Class Class1 Inherits System.Xml.XmlAttribute Sub New() MyBase.New(Nothing, Nothing, Nothing, Nothing) End Sub Sub goo() End Sub Public bar As ClassLibrary3.Class1 End Class "; private const string FileInLibraryProject3 = @"Public Class Class1 Public Enum E E1 E2 End Enum Public Function Goo() As ADODB.Recordset Dim x As ADODB.Recordset = Nothing Return x End Function End Class "; private const string FileInConsoleProject1 = @" class Program { static void Main(string[] args) { var y = new ClassLibrary1.class2(); y.goo(null); y.ee += (_, __) => { }; var x = new ClassLibrary1.Class1(); ClassLibrary1.class3 z = null; var a = new ClassLibrary2.Class1(); var d = a.bar; } } "; private const string ClassLibrary1Name = "ClassLibrary1"; private const string ClassLibrary2Name = "ClassLibrary2"; private const string ClassLibrary3Name = "ClassLibrary3"; private const string ConsoleProjectName = "ConsoleApplication1"; protected override string LanguageName => LanguageNames.CSharp; public CSharpAddMissingReference(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.SolutionExplorer.CreateSolution("ReferenceErrors", solutionElement: XElement.Parse( "<Solution>" + $" <Project ProjectName=\"{ClassLibrary1Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.WinFormsApplication}\" Language=\"{LanguageNames.VisualBasic}\">" + " <Document FileName=\"Class1.vb\"><![CDATA[" + FileInLibraryProject1 + "]]>" + " </Document>" + " </Project>" + $" <Project ProjectName=\"{ClassLibrary2Name}\" ProjectReferences=\"{ClassLibrary3Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.ClassLibrary}\" Language=\"{LanguageNames.VisualBasic}\">" + " <Document FileName=\"Class1.vb\"><![CDATA[" + FileInLibraryProject2 + "]]>" + " </Document>" + " </Project>" + $" <Project ProjectName=\"{ClassLibrary3Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.ClassLibrary}\" Language=\"{LanguageNames.VisualBasic}\">" + " <Document FileName=\"Class1.vb\"><![CDATA[" + FileInLibraryProject3 + "]]>" + " </Document>" + " </Project>" + $" <Project ProjectName=\"{ConsoleProjectName}\" ProjectReferences=\"{ClassLibrary1Name};{ClassLibrary2Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.ConsoleApplication}\" Language=\"{LanguageNames.CSharp}\">" + " <Document FileName=\"Program.cs\"><![CDATA[" + FileInConsoleProject1 + "]]>" + " </Document>" + " </Project>" + "</Solution>")); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingReference)] public void VerifyAvailableCodeActions() { var consoleProject = new ProjectUtils.Project(ConsoleProjectName); VisualStudio.SolutionExplorer.OpenFile(consoleProject, "Program.cs"); VisualStudio.Editor.PlaceCaret("y.goo", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add reference to 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.", applyFix: false); VisualStudio.Editor.PlaceCaret("y.ee", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add reference to 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.", applyFix: false); VisualStudio.Editor.PlaceCaret("a.bar", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add project reference to 'ClassLibrary3'.", applyFix: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingReference)] public void InvokeSomeFixesInCSharpThenVerifyReferences() { var consoleProject = new ProjectUtils.Project(ConsoleProjectName); VisualStudio.SolutionExplorer.OpenFile(consoleProject, "Program.cs"); VisualStudio.Editor.PlaceCaret("y.goo", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add reference to 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.", applyFix: true); VisualStudio.SolutionExplorer.Verify.AssemblyReferencePresent( project: consoleProject, assemblyName: "System.Windows.Forms", assemblyVersion: "4.0.0.0", assemblyPublicKeyToken: "b77a5c561934e089"); VisualStudio.Editor.PlaceCaret("a.bar", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add project reference to 'ClassLibrary3'.", applyFix: true); VisualStudio.SolutionExplorer.Verify.ProjectReferencePresent( project: consoleProject, referencedProjectName: ClassLibrary3Name); } } }
// 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 System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpAddMissingReference : AbstractEditorTest { private const string FileInLibraryProject1 = @"Public Class Class1 Inherits System.Windows.Forms.Form Public Sub goo() End Sub End Class Public Class class2 Public Sub goo(ByVal x As System.Windows.Forms.Form) End Sub Public Event ee As System.Windows.Forms.ColumnClickEventHandler End Class Public Class class3 Implements System.Windows.Forms.IButtonControl Public Property DialogResult() As System.Windows.Forms.DialogResult Implements System.Windows.Forms.IButtonControl.DialogResult Get End Get Set(ByVal Value As System.Windows.Forms.DialogResult) End Set End Property Public Sub NotifyDefault(ByVal value As Boolean) Implements System.Windows.Forms.IButtonControl.NotifyDefault End Sub Public Sub PerformClick() Implements System.Windows.Forms.IButtonControl.PerformClick End Sub End Class "; private const string FileInLibraryProject2 = @"Public Class Class1 Inherits System.Xml.XmlAttribute Sub New() MyBase.New(Nothing, Nothing, Nothing, Nothing) End Sub Sub goo() End Sub Public bar As ClassLibrary3.Class1 End Class "; private const string FileInLibraryProject3 = @"Public Class Class1 Public Enum E E1 E2 End Enum Public Function Goo() As ADODB.Recordset Dim x As ADODB.Recordset = Nothing Return x End Function End Class "; private const string FileInConsoleProject1 = @" class Program { static void Main(string[] args) { var y = new ClassLibrary1.class2(); y.goo(null); y.ee += (_, __) => { }; var x = new ClassLibrary1.Class1(); ClassLibrary1.class3 z = null; var a = new ClassLibrary2.Class1(); var d = a.bar; } } "; private const string ClassLibrary1Name = "ClassLibrary1"; private const string ClassLibrary2Name = "ClassLibrary2"; private const string ClassLibrary3Name = "ClassLibrary3"; private const string ConsoleProjectName = "ConsoleApplication1"; protected override string LanguageName => LanguageNames.CSharp; public CSharpAddMissingReference(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.SolutionExplorer.CreateSolution("ReferenceErrors", solutionElement: XElement.Parse( "<Solution>" + $" <Project ProjectName=\"{ClassLibrary1Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.WinFormsApplication}\" Language=\"{LanguageNames.VisualBasic}\">" + " <Document FileName=\"Class1.vb\"><![CDATA[" + FileInLibraryProject1 + "]]>" + " </Document>" + " </Project>" + $" <Project ProjectName=\"{ClassLibrary2Name}\" ProjectReferences=\"{ClassLibrary3Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.ClassLibrary}\" Language=\"{LanguageNames.VisualBasic}\">" + " <Document FileName=\"Class1.vb\"><![CDATA[" + FileInLibraryProject2 + "]]>" + " </Document>" + " </Project>" + $" <Project ProjectName=\"{ClassLibrary3Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.ClassLibrary}\" Language=\"{LanguageNames.VisualBasic}\">" + " <Document FileName=\"Class1.vb\"><![CDATA[" + FileInLibraryProject3 + "]]>" + " </Document>" + " </Project>" + $" <Project ProjectName=\"{ConsoleProjectName}\" ProjectReferences=\"{ClassLibrary1Name};{ClassLibrary2Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.ConsoleApplication}\" Language=\"{LanguageNames.CSharp}\">" + " <Document FileName=\"Program.cs\"><![CDATA[" + FileInConsoleProject1 + "]]>" + " </Document>" + " </Project>" + "</Solution>")); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingReference)] public void VerifyAvailableCodeActions() { var consoleProject = new ProjectUtils.Project(ConsoleProjectName); VisualStudio.SolutionExplorer.OpenFile(consoleProject, "Program.cs"); VisualStudio.Editor.PlaceCaret("y.goo", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add reference to 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.", applyFix: false); VisualStudio.Editor.PlaceCaret("y.ee", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add reference to 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.", applyFix: false); VisualStudio.Editor.PlaceCaret("a.bar", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add project reference to 'ClassLibrary3'.", applyFix: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingReference)] public void InvokeSomeFixesInCSharpThenVerifyReferences() { var consoleProject = new ProjectUtils.Project(ConsoleProjectName); VisualStudio.SolutionExplorer.OpenFile(consoleProject, "Program.cs"); VisualStudio.Editor.PlaceCaret("y.goo", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add reference to 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.", applyFix: true); VisualStudio.SolutionExplorer.Verify.AssemblyReferencePresent( project: consoleProject, assemblyName: "System.Windows.Forms", assemblyVersion: "4.0.0.0", assemblyPublicKeyToken: "b77a5c561934e089"); VisualStudio.Editor.PlaceCaret("a.bar", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add project reference to 'ClassLibrary3'.", applyFix: true); VisualStudio.SolutionExplorer.Verify.ProjectReferencePresent( project: consoleProject, referencedProjectName: ClassLibrary3Name); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Sources/UserDefinedBinaryOperators.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. Public Structure UserDefinedBinaryOperator{2} Public Shared Operator +(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator -(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator *(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator /(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator \(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Mod(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator ^(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator =(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <>(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator >(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <=(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator >=(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Like(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator &(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator And(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Or(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Xor(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <<(x As UserDefinedBinaryOperator{2}{0}, y As Integer) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator >>(x As UserDefinedBinaryOperator{2}{0}, y As Integer) As UserDefinedBinaryOperator{2} Return x End Operator End Structure
' 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. Public Structure UserDefinedBinaryOperator{2} Public Shared Operator +(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator -(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator *(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator /(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator \(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Mod(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator ^(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator =(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <>(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator >(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <=(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator >=(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Like(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator &(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator And(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Or(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Xor(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <<(x As UserDefinedBinaryOperator{2}{0}, y As Integer) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator >>(x As UserDefinedBinaryOperator{2}{0}, y As Integer) As UserDefinedBinaryOperator{2} Return x End Operator End Structure
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/EditorFeatures/CSharpTest/Structure/SwitchStatementStructureTests.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.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class SwitchStatementStructureTests : AbstractCSharpSyntaxNodeStructureTests<SwitchStatementSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new SwitchStatementStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSwitchStatement1() { const string code = @" class C { void M() { {|hint:$$switch (expr){|textspan: { }|}|} } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } } }
// 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.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class SwitchStatementStructureTests : AbstractCSharpSyntaxNodeStructureTests<SwitchStatementSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new SwitchStatementStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSwitchStatement1() { const string code = @" class C { void M() { {|hint:$$switch (expr){|textspan: { }|}|} } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Workspaces/Remote/ServiceHub/Host/TemporaryWorkspace.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 Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// this lets us have isolated workspace services between solutions such as option services. /// /// otherwise, mutating service in one service call such as changing options, can affect result of other service call /// </summary> internal class TemporaryWorkspace : Workspace { public TemporaryWorkspace(HostServices hostServices, string? workspaceKind, SolutionInfo solutionInfo, SerializableOptionSet options) : base(hostServices, workspaceKind) { SetOptions(Options.WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0)); var documentOptionsProviderFactories = ((IMefHostExportProvider)Services.HostServices).GetExports<IDocumentOptionsProviderFactory, OrderableMetadata>(); RegisterDocumentOptionProviders(documentOptionsProviderFactories); OnSolutionAdded(solutionInfo); SetCurrentSolution(CurrentSolution.WithOptions(options)); } } }
// 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 Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// this lets us have isolated workspace services between solutions such as option services. /// /// otherwise, mutating service in one service call such as changing options, can affect result of other service call /// </summary> internal class TemporaryWorkspace : Workspace { public TemporaryWorkspace(HostServices hostServices, string? workspaceKind, SolutionInfo solutionInfo, SerializableOptionSet options) : base(hostServices, workspaceKind) { SetOptions(Options.WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0)); var documentOptionsProviderFactories = ((IMefHostExportProvider)Services.HostServices).GetExports<IDocumentOptionsProviderFactory, OrderableMetadata>(); RegisterDocumentOptionProviders(documentOptionsProviderFactories); OnSolutionAdded(solutionInfo); SetCurrentSolution(CurrentSolution.WithOptions(options)); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Tests/TestConversion_TypeMatrix_UserTypes.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 Imports System.Linq.Expressions Public Class Clazz1 End Class Public Class Clazz2 Inherits Clazz1 End Class Public Structure Struct1 End Structure Public Class TestClass Public Sub Test() Console.WriteLine("-=-=-=-=-=-=-=-=- Object -> Object -=-=-=-=-=-=-=-=-") Dim exprtree1 As Expression(Of Func(Of Object, Object)) = Function(x As Object) x Console.WriteLine(exprtree1.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Object, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree2 As Expression(Of Func(Of Object, Object)) = Function(x As Object) CType(x, Object) Console.WriteLine(exprtree2.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Object, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree3 As Expression(Of Func(Of Object, Object)) = Function(x As Object) DirectCast(x, Object) Console.WriteLine(exprtree3.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Object, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree4 As Expression(Of Func(Of Object, Object)) = Function(x As Object) TryCast(x, Object) Console.WriteLine(exprtree4.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CObj(Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree5 As Expression(Of Func(Of Object, Object)) = Function(x As Object) CObj(x) Console.WriteLine(exprtree5.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Object -> String -=-=-=-=-=-=-=-=-") Dim exprtree6 As Expression(Of Func(Of Object, String)) = Function(x As Object) x Console.WriteLine(exprtree6.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Object, String) -> String -=-=-=-=-=-=-=-=-") Dim exprtree7 As Expression(Of Func(Of Object, String)) = Function(x As Object) CType(x, String) Console.WriteLine(exprtree7.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Object, String) -> String -=-=-=-=-=-=-=-=-") Dim exprtree8 As Expression(Of Func(Of Object, String)) = Function(x As Object) DirectCast(x, String) Console.WriteLine(exprtree8.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CStr(Object) -> String -=-=-=-=-=-=-=-=-") Dim exprtree9 As Expression(Of Func(Of Object, String)) = Function(x As Object) CStr(x) Console.WriteLine(exprtree9.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Object -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree10 As Expression(Of Func(Of Object, Struct1)) = Function(x As Object) x Console.WriteLine(exprtree10.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Object, Struct1) -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree11 As Expression(Of Func(Of Object, Struct1)) = Function(x As Object) CType(x, Struct1) Console.WriteLine(exprtree11.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Object, Struct1) -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree12 As Expression(Of Func(Of Object, Struct1)) = Function(x As Object) DirectCast(x, Struct1) Console.WriteLine(exprtree12.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Object -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree13 As Expression(Of Func(Of Object, Struct1?)) = Function(x As Object) x Console.WriteLine(exprtree13.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Object, Struct1?) -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree14 As Expression(Of Func(Of Object, Struct1?)) = Function(x As Object) CType(x, Struct1?) Console.WriteLine(exprtree14.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Object, Struct1?) -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree15 As Expression(Of Func(Of Object, Struct1?)) = Function(x As Object) DirectCast(x, Struct1?) Console.WriteLine(exprtree15.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Object -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree16 As Expression(Of Func(Of Object, Clazz1)) = Function(x As Object) x Console.WriteLine(exprtree16.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Object, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree17 As Expression(Of Func(Of Object, Clazz1)) = Function(x As Object) CType(x, Clazz1) Console.WriteLine(exprtree17.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Object, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree18 As Expression(Of Func(Of Object, Clazz1)) = Function(x As Object) DirectCast(x, Clazz1) Console.WriteLine(exprtree18.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Object, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree19 As Expression(Of Func(Of Object, Clazz1)) = Function(x As Object) TryCast(x, Clazz1) Console.WriteLine(exprtree19.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Object -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree20 As Expression(Of Func(Of Object, Clazz2)) = Function(x As Object) x Console.WriteLine(exprtree20.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Object, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree21 As Expression(Of Func(Of Object, Clazz2)) = Function(x As Object) CType(x, Clazz2) Console.WriteLine(exprtree21.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Object, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree22 As Expression(Of Func(Of Object, Clazz2)) = Function(x As Object) DirectCast(x, Clazz2) Console.WriteLine(exprtree22.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Object, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree23 As Expression(Of Func(Of Object, Clazz2)) = Function(x As Object) TryCast(x, Clazz2) Console.WriteLine(exprtree23.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- String -> Object -=-=-=-=-=-=-=-=-") Dim exprtree24 As Expression(Of Func(Of String, Object)) = Function(x As String) x Console.WriteLine(exprtree24.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(String, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree25 As Expression(Of Func(Of String, Object)) = Function(x As String) CType(x, Object) Console.WriteLine(exprtree25.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(String, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree26 As Expression(Of Func(Of String, Object)) = Function(x As String) DirectCast(x, Object) Console.WriteLine(exprtree26.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(String, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree27 As Expression(Of Func(Of String, Object)) = Function(x As String) TryCast(x, Object) Console.WriteLine(exprtree27.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CObj(String) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree28 As Expression(Of Func(Of String, Object)) = Function(x As String) CObj(x) Console.WriteLine(exprtree28.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- String -> String -=-=-=-=-=-=-=-=-") Dim exprtree29 As Expression(Of Func(Of String, String)) = Function(x As String) x Console.WriteLine(exprtree29.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(String, String) -> String -=-=-=-=-=-=-=-=-") Dim exprtree30 As Expression(Of Func(Of String, String)) = Function(x As String) CType(x, String) Console.WriteLine(exprtree30.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(String, String) -> String -=-=-=-=-=-=-=-=-") Dim exprtree31 As Expression(Of Func(Of String, String)) = Function(x As String) DirectCast(x, String) Console.WriteLine(exprtree31.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CStr(String) -> String -=-=-=-=-=-=-=-=-") Dim exprtree32 As Expression(Of Func(Of String, String)) = Function(x As String) CStr(x) Console.WriteLine(exprtree32.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Struct1 -> Object -=-=-=-=-=-=-=-=-") Dim exprtree47 As Expression(Of Func(Of Struct1, Object)) = Function(x As Struct1) x Console.WriteLine(exprtree47.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Struct1, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree48 As Expression(Of Func(Of Struct1, Object)) = Function(x As Struct1) CType(x, Object) Console.WriteLine(exprtree48.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Struct1, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree49 As Expression(Of Func(Of Struct1, Object)) = Function(x As Struct1) DirectCast(x, Object) Console.WriteLine(exprtree49.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Struct1, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree50 As Expression(Of Func(Of Struct1, Object)) = Function(x As Struct1) TryCast(x, Object) Console.WriteLine(exprtree50.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CObj(Struct1) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree51 As Expression(Of Func(Of Struct1, Object)) = Function(x As Struct1) CObj(x) Console.WriteLine(exprtree51.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Struct1 -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree56 As Expression(Of Func(Of Struct1, Struct1)) = Function(x As Struct1) x Console.WriteLine(exprtree56.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Struct1, Struct1) -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree57 As Expression(Of Func(Of Struct1, Struct1)) = Function(x As Struct1) CType(x, Struct1) Console.WriteLine(exprtree57.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Struct1, Struct1) -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree58 As Expression(Of Func(Of Struct1, Struct1)) = Function(x As Struct1) DirectCast(x, Struct1) Console.WriteLine(exprtree58.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Struct1 -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree59 As Expression(Of Func(Of Struct1, Struct1?)) = Function(x As Struct1) x Console.WriteLine(exprtree59.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Struct1, Struct1?) -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree60 As Expression(Of Func(Of Struct1, Struct1?)) = Function(x As Struct1) CType(x, Struct1?) Console.WriteLine(exprtree60.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Struct1? -> Object -=-=-=-=-=-=-=-=-") Dim exprtree70 As Expression(Of Func(Of Struct1?, Object)) = Function(x As Struct1?) x Console.WriteLine(exprtree70.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Struct1?, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree71 As Expression(Of Func(Of Struct1?, Object)) = Function(x As Struct1?) CType(x, Object) Console.WriteLine(exprtree71.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Struct1?, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree72 As Expression(Of Func(Of Struct1?, Object)) = Function(x As Struct1?) DirectCast(x, Object) Console.WriteLine(exprtree72.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Struct1?, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree73 As Expression(Of Func(Of Struct1?, Object)) = Function(x As Struct1?) TryCast(x, Object) Console.WriteLine(exprtree73.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CObj(Struct1?) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree74 As Expression(Of Func(Of Struct1?, Object)) = Function(x As Struct1?) CObj(x) Console.WriteLine(exprtree74.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Struct1? -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree79 As Expression(Of Func(Of Struct1?, Struct1)) = Function(x As Struct1?) x Console.WriteLine(exprtree79.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Struct1?, Struct1) -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree80 As Expression(Of Func(Of Struct1?, Struct1)) = Function(x As Struct1?) CType(x, Struct1) Console.WriteLine(exprtree80.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Struct1? -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree82 As Expression(Of Func(Of Struct1?, Struct1?)) = Function(x As Struct1?) x Console.WriteLine(exprtree82.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Struct1?, Struct1?) -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree83 As Expression(Of Func(Of Struct1?, Struct1?)) = Function(x As Struct1?) CType(x, Struct1?) Console.WriteLine(exprtree83.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Struct1?, Struct1?) -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree84 As Expression(Of Func(Of Struct1?, Struct1?)) = Function(x As Struct1?) DirectCast(x, Struct1?) Console.WriteLine(exprtree84.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Clazz1 -> Object -=-=-=-=-=-=-=-=-") Dim exprtree93 As Expression(Of Func(Of Clazz1, Object)) = Function(x As Clazz1) x Console.WriteLine(exprtree93.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Clazz1, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree94 As Expression(Of Func(Of Clazz1, Object)) = Function(x As Clazz1) CType(x, Object) Console.WriteLine(exprtree94.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Clazz1, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree95 As Expression(Of Func(Of Clazz1, Object)) = Function(x As Clazz1) DirectCast(x, Object) Console.WriteLine(exprtree95.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Clazz1, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree96 As Expression(Of Func(Of Clazz1, Object)) = Function(x As Clazz1) TryCast(x, Object) Console.WriteLine(exprtree96.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CObj(Clazz1) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree97 As Expression(Of Func(Of Clazz1, Object)) = Function(x As Clazz1) CObj(x) Console.WriteLine(exprtree97.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Clazz1 -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree108 As Expression(Of Func(Of Clazz1, Clazz1)) = Function(x As Clazz1) x Console.WriteLine(exprtree108.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Clazz1, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree109 As Expression(Of Func(Of Clazz1, Clazz1)) = Function(x As Clazz1) CType(x, Clazz1) Console.WriteLine(exprtree109.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Clazz1, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree110 As Expression(Of Func(Of Clazz1, Clazz1)) = Function(x As Clazz1) DirectCast(x, Clazz1) Console.WriteLine(exprtree110.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Clazz1, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree111 As Expression(Of Func(Of Clazz1, Clazz1)) = Function(x As Clazz1) TryCast(x, Clazz1) Console.WriteLine(exprtree111.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Clazz1 -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree112 As Expression(Of Func(Of Clazz1, Clazz2)) = Function(x As Clazz1) x Console.WriteLine(exprtree112.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Clazz1, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree113 As Expression(Of Func(Of Clazz1, Clazz2)) = Function(x As Clazz1) CType(x, Clazz2) Console.WriteLine(exprtree113.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Clazz1, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree114 As Expression(Of Func(Of Clazz1, Clazz2)) = Function(x As Clazz1) DirectCast(x, Clazz2) Console.WriteLine(exprtree114.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Clazz1, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree115 As Expression(Of Func(Of Clazz1, Clazz2)) = Function(x As Clazz1) TryCast(x, Clazz2) Console.WriteLine(exprtree115.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Clazz2 -> Object -=-=-=-=-=-=-=-=-") Dim exprtree116 As Expression(Of Func(Of Clazz2, Object)) = Function(x As Clazz2) x Console.WriteLine(exprtree116.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Clazz2, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree117 As Expression(Of Func(Of Clazz2, Object)) = Function(x As Clazz2) CType(x, Object) Console.WriteLine(exprtree117.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Clazz2, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree118 As Expression(Of Func(Of Clazz2, Object)) = Function(x As Clazz2) DirectCast(x, Object) Console.WriteLine(exprtree118.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Clazz2, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree119 As Expression(Of Func(Of Clazz2, Object)) = Function(x As Clazz2) TryCast(x, Object) Console.WriteLine(exprtree119.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CObj(Clazz2) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree120 As Expression(Of Func(Of Clazz2, Object)) = Function(x As Clazz2) CObj(x) Console.WriteLine(exprtree120.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Clazz2 -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree131 As Expression(Of Func(Of Clazz2, Clazz1)) = Function(x As Clazz2) x Console.WriteLine(exprtree131.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Clazz2, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree132 As Expression(Of Func(Of Clazz2, Clazz1)) = Function(x As Clazz2) CType(x, Clazz1) Console.WriteLine(exprtree132.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Clazz2, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree133 As Expression(Of Func(Of Clazz2, Clazz1)) = Function(x As Clazz2) DirectCast(x, Clazz1) Console.WriteLine(exprtree133.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Clazz2, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree134 As Expression(Of Func(Of Clazz2, Clazz1)) = Function(x As Clazz2) TryCast(x, Clazz1) Console.WriteLine(exprtree134.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Clazz2 -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree135 As Expression(Of Func(Of Clazz2, Clazz2)) = Function(x As Clazz2) x Console.WriteLine(exprtree135.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Clazz2, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree136 As Expression(Of Func(Of Clazz2, Clazz2)) = Function(x As Clazz2) CType(x, Clazz2) Console.WriteLine(exprtree136.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Clazz2, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree137 As Expression(Of Func(Of Clazz2, Clazz2)) = Function(x As Clazz2) DirectCast(x, Clazz2) Console.WriteLine(exprtree137.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Clazz2, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree138 As Expression(Of Func(Of Clazz2, Clazz2)) = Function(x As Clazz2) TryCast(x, Clazz2) Console.WriteLine(exprtree138.Dump) End Sub End Class Module Form1 Sub Main() Dim inst As New TestClass() inst.Test() End Sub End Module
' 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 Imports System.Linq.Expressions Public Class Clazz1 End Class Public Class Clazz2 Inherits Clazz1 End Class Public Structure Struct1 End Structure Public Class TestClass Public Sub Test() Console.WriteLine("-=-=-=-=-=-=-=-=- Object -> Object -=-=-=-=-=-=-=-=-") Dim exprtree1 As Expression(Of Func(Of Object, Object)) = Function(x As Object) x Console.WriteLine(exprtree1.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Object, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree2 As Expression(Of Func(Of Object, Object)) = Function(x As Object) CType(x, Object) Console.WriteLine(exprtree2.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Object, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree3 As Expression(Of Func(Of Object, Object)) = Function(x As Object) DirectCast(x, Object) Console.WriteLine(exprtree3.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Object, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree4 As Expression(Of Func(Of Object, Object)) = Function(x As Object) TryCast(x, Object) Console.WriteLine(exprtree4.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CObj(Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree5 As Expression(Of Func(Of Object, Object)) = Function(x As Object) CObj(x) Console.WriteLine(exprtree5.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Object -> String -=-=-=-=-=-=-=-=-") Dim exprtree6 As Expression(Of Func(Of Object, String)) = Function(x As Object) x Console.WriteLine(exprtree6.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Object, String) -> String -=-=-=-=-=-=-=-=-") Dim exprtree7 As Expression(Of Func(Of Object, String)) = Function(x As Object) CType(x, String) Console.WriteLine(exprtree7.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Object, String) -> String -=-=-=-=-=-=-=-=-") Dim exprtree8 As Expression(Of Func(Of Object, String)) = Function(x As Object) DirectCast(x, String) Console.WriteLine(exprtree8.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CStr(Object) -> String -=-=-=-=-=-=-=-=-") Dim exprtree9 As Expression(Of Func(Of Object, String)) = Function(x As Object) CStr(x) Console.WriteLine(exprtree9.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Object -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree10 As Expression(Of Func(Of Object, Struct1)) = Function(x As Object) x Console.WriteLine(exprtree10.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Object, Struct1) -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree11 As Expression(Of Func(Of Object, Struct1)) = Function(x As Object) CType(x, Struct1) Console.WriteLine(exprtree11.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Object, Struct1) -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree12 As Expression(Of Func(Of Object, Struct1)) = Function(x As Object) DirectCast(x, Struct1) Console.WriteLine(exprtree12.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Object -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree13 As Expression(Of Func(Of Object, Struct1?)) = Function(x As Object) x Console.WriteLine(exprtree13.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Object, Struct1?) -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree14 As Expression(Of Func(Of Object, Struct1?)) = Function(x As Object) CType(x, Struct1?) Console.WriteLine(exprtree14.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Object, Struct1?) -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree15 As Expression(Of Func(Of Object, Struct1?)) = Function(x As Object) DirectCast(x, Struct1?) Console.WriteLine(exprtree15.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Object -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree16 As Expression(Of Func(Of Object, Clazz1)) = Function(x As Object) x Console.WriteLine(exprtree16.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Object, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree17 As Expression(Of Func(Of Object, Clazz1)) = Function(x As Object) CType(x, Clazz1) Console.WriteLine(exprtree17.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Object, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree18 As Expression(Of Func(Of Object, Clazz1)) = Function(x As Object) DirectCast(x, Clazz1) Console.WriteLine(exprtree18.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Object, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree19 As Expression(Of Func(Of Object, Clazz1)) = Function(x As Object) TryCast(x, Clazz1) Console.WriteLine(exprtree19.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Object -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree20 As Expression(Of Func(Of Object, Clazz2)) = Function(x As Object) x Console.WriteLine(exprtree20.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Object, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree21 As Expression(Of Func(Of Object, Clazz2)) = Function(x As Object) CType(x, Clazz2) Console.WriteLine(exprtree21.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Object, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree22 As Expression(Of Func(Of Object, Clazz2)) = Function(x As Object) DirectCast(x, Clazz2) Console.WriteLine(exprtree22.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Object, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree23 As Expression(Of Func(Of Object, Clazz2)) = Function(x As Object) TryCast(x, Clazz2) Console.WriteLine(exprtree23.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- String -> Object -=-=-=-=-=-=-=-=-") Dim exprtree24 As Expression(Of Func(Of String, Object)) = Function(x As String) x Console.WriteLine(exprtree24.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(String, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree25 As Expression(Of Func(Of String, Object)) = Function(x As String) CType(x, Object) Console.WriteLine(exprtree25.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(String, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree26 As Expression(Of Func(Of String, Object)) = Function(x As String) DirectCast(x, Object) Console.WriteLine(exprtree26.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(String, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree27 As Expression(Of Func(Of String, Object)) = Function(x As String) TryCast(x, Object) Console.WriteLine(exprtree27.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CObj(String) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree28 As Expression(Of Func(Of String, Object)) = Function(x As String) CObj(x) Console.WriteLine(exprtree28.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- String -> String -=-=-=-=-=-=-=-=-") Dim exprtree29 As Expression(Of Func(Of String, String)) = Function(x As String) x Console.WriteLine(exprtree29.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(String, String) -> String -=-=-=-=-=-=-=-=-") Dim exprtree30 As Expression(Of Func(Of String, String)) = Function(x As String) CType(x, String) Console.WriteLine(exprtree30.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(String, String) -> String -=-=-=-=-=-=-=-=-") Dim exprtree31 As Expression(Of Func(Of String, String)) = Function(x As String) DirectCast(x, String) Console.WriteLine(exprtree31.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CStr(String) -> String -=-=-=-=-=-=-=-=-") Dim exprtree32 As Expression(Of Func(Of String, String)) = Function(x As String) CStr(x) Console.WriteLine(exprtree32.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Struct1 -> Object -=-=-=-=-=-=-=-=-") Dim exprtree47 As Expression(Of Func(Of Struct1, Object)) = Function(x As Struct1) x Console.WriteLine(exprtree47.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Struct1, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree48 As Expression(Of Func(Of Struct1, Object)) = Function(x As Struct1) CType(x, Object) Console.WriteLine(exprtree48.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Struct1, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree49 As Expression(Of Func(Of Struct1, Object)) = Function(x As Struct1) DirectCast(x, Object) Console.WriteLine(exprtree49.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Struct1, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree50 As Expression(Of Func(Of Struct1, Object)) = Function(x As Struct1) TryCast(x, Object) Console.WriteLine(exprtree50.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CObj(Struct1) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree51 As Expression(Of Func(Of Struct1, Object)) = Function(x As Struct1) CObj(x) Console.WriteLine(exprtree51.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Struct1 -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree56 As Expression(Of Func(Of Struct1, Struct1)) = Function(x As Struct1) x Console.WriteLine(exprtree56.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Struct1, Struct1) -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree57 As Expression(Of Func(Of Struct1, Struct1)) = Function(x As Struct1) CType(x, Struct1) Console.WriteLine(exprtree57.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Struct1, Struct1) -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree58 As Expression(Of Func(Of Struct1, Struct1)) = Function(x As Struct1) DirectCast(x, Struct1) Console.WriteLine(exprtree58.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Struct1 -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree59 As Expression(Of Func(Of Struct1, Struct1?)) = Function(x As Struct1) x Console.WriteLine(exprtree59.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Struct1, Struct1?) -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree60 As Expression(Of Func(Of Struct1, Struct1?)) = Function(x As Struct1) CType(x, Struct1?) Console.WriteLine(exprtree60.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Struct1? -> Object -=-=-=-=-=-=-=-=-") Dim exprtree70 As Expression(Of Func(Of Struct1?, Object)) = Function(x As Struct1?) x Console.WriteLine(exprtree70.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Struct1?, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree71 As Expression(Of Func(Of Struct1?, Object)) = Function(x As Struct1?) CType(x, Object) Console.WriteLine(exprtree71.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Struct1?, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree72 As Expression(Of Func(Of Struct1?, Object)) = Function(x As Struct1?) DirectCast(x, Object) Console.WriteLine(exprtree72.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Struct1?, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree73 As Expression(Of Func(Of Struct1?, Object)) = Function(x As Struct1?) TryCast(x, Object) Console.WriteLine(exprtree73.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CObj(Struct1?) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree74 As Expression(Of Func(Of Struct1?, Object)) = Function(x As Struct1?) CObj(x) Console.WriteLine(exprtree74.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Struct1? -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree79 As Expression(Of Func(Of Struct1?, Struct1)) = Function(x As Struct1?) x Console.WriteLine(exprtree79.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Struct1?, Struct1) -> Struct1 -=-=-=-=-=-=-=-=-") Dim exprtree80 As Expression(Of Func(Of Struct1?, Struct1)) = Function(x As Struct1?) CType(x, Struct1) Console.WriteLine(exprtree80.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Struct1? -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree82 As Expression(Of Func(Of Struct1?, Struct1?)) = Function(x As Struct1?) x Console.WriteLine(exprtree82.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Struct1?, Struct1?) -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree83 As Expression(Of Func(Of Struct1?, Struct1?)) = Function(x As Struct1?) CType(x, Struct1?) Console.WriteLine(exprtree83.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Struct1?, Struct1?) -> Struct1? -=-=-=-=-=-=-=-=-") Dim exprtree84 As Expression(Of Func(Of Struct1?, Struct1?)) = Function(x As Struct1?) DirectCast(x, Struct1?) Console.WriteLine(exprtree84.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Clazz1 -> Object -=-=-=-=-=-=-=-=-") Dim exprtree93 As Expression(Of Func(Of Clazz1, Object)) = Function(x As Clazz1) x Console.WriteLine(exprtree93.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Clazz1, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree94 As Expression(Of Func(Of Clazz1, Object)) = Function(x As Clazz1) CType(x, Object) Console.WriteLine(exprtree94.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Clazz1, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree95 As Expression(Of Func(Of Clazz1, Object)) = Function(x As Clazz1) DirectCast(x, Object) Console.WriteLine(exprtree95.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Clazz1, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree96 As Expression(Of Func(Of Clazz1, Object)) = Function(x As Clazz1) TryCast(x, Object) Console.WriteLine(exprtree96.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CObj(Clazz1) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree97 As Expression(Of Func(Of Clazz1, Object)) = Function(x As Clazz1) CObj(x) Console.WriteLine(exprtree97.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Clazz1 -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree108 As Expression(Of Func(Of Clazz1, Clazz1)) = Function(x As Clazz1) x Console.WriteLine(exprtree108.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Clazz1, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree109 As Expression(Of Func(Of Clazz1, Clazz1)) = Function(x As Clazz1) CType(x, Clazz1) Console.WriteLine(exprtree109.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Clazz1, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree110 As Expression(Of Func(Of Clazz1, Clazz1)) = Function(x As Clazz1) DirectCast(x, Clazz1) Console.WriteLine(exprtree110.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Clazz1, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree111 As Expression(Of Func(Of Clazz1, Clazz1)) = Function(x As Clazz1) TryCast(x, Clazz1) Console.WriteLine(exprtree111.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Clazz1 -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree112 As Expression(Of Func(Of Clazz1, Clazz2)) = Function(x As Clazz1) x Console.WriteLine(exprtree112.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Clazz1, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree113 As Expression(Of Func(Of Clazz1, Clazz2)) = Function(x As Clazz1) CType(x, Clazz2) Console.WriteLine(exprtree113.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Clazz1, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree114 As Expression(Of Func(Of Clazz1, Clazz2)) = Function(x As Clazz1) DirectCast(x, Clazz2) Console.WriteLine(exprtree114.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Clazz1, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree115 As Expression(Of Func(Of Clazz1, Clazz2)) = Function(x As Clazz1) TryCast(x, Clazz2) Console.WriteLine(exprtree115.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Clazz2 -> Object -=-=-=-=-=-=-=-=-") Dim exprtree116 As Expression(Of Func(Of Clazz2, Object)) = Function(x As Clazz2) x Console.WriteLine(exprtree116.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Clazz2, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree117 As Expression(Of Func(Of Clazz2, Object)) = Function(x As Clazz2) CType(x, Object) Console.WriteLine(exprtree117.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Clazz2, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree118 As Expression(Of Func(Of Clazz2, Object)) = Function(x As Clazz2) DirectCast(x, Object) Console.WriteLine(exprtree118.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Clazz2, Object) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree119 As Expression(Of Func(Of Clazz2, Object)) = Function(x As Clazz2) TryCast(x, Object) Console.WriteLine(exprtree119.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CObj(Clazz2) -> Object -=-=-=-=-=-=-=-=-") Dim exprtree120 As Expression(Of Func(Of Clazz2, Object)) = Function(x As Clazz2) CObj(x) Console.WriteLine(exprtree120.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Clazz2 -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree131 As Expression(Of Func(Of Clazz2, Clazz1)) = Function(x As Clazz2) x Console.WriteLine(exprtree131.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Clazz2, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree132 As Expression(Of Func(Of Clazz2, Clazz1)) = Function(x As Clazz2) CType(x, Clazz1) Console.WriteLine(exprtree132.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Clazz2, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree133 As Expression(Of Func(Of Clazz2, Clazz1)) = Function(x As Clazz2) DirectCast(x, Clazz1) Console.WriteLine(exprtree133.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Clazz2, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=-") Dim exprtree134 As Expression(Of Func(Of Clazz2, Clazz1)) = Function(x As Clazz2) TryCast(x, Clazz1) Console.WriteLine(exprtree134.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- Clazz2 -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree135 As Expression(Of Func(Of Clazz2, Clazz2)) = Function(x As Clazz2) x Console.WriteLine(exprtree135.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Clazz2, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree136 As Expression(Of Func(Of Clazz2, Clazz2)) = Function(x As Clazz2) CType(x, Clazz2) Console.WriteLine(exprtree136.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Clazz2, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree137 As Expression(Of Func(Of Clazz2, Clazz2)) = Function(x As Clazz2) DirectCast(x, Clazz2) Console.WriteLine(exprtree137.Dump) Console.WriteLine("-=-=-=-=-=-=-=-=- TryCast(Clazz2, Clazz2) -> Clazz2 -=-=-=-=-=-=-=-=-") Dim exprtree138 As Expression(Of Func(Of Clazz2, Clazz2)) = Function(x As Clazz2) TryCast(x, Clazz2) Console.WriteLine(exprtree138.Dump) End Sub End Class Module Form1 Sub Main() Dim inst As New TestClass() inst.Test() End Sub End Module
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/Core/Portable/LanguageServices/AnonymousTypeDisplayService/IAnonymousTypeDisplayService.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.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.LanguageServices { internal interface IAnonymousTypeDisplayService : ILanguageService { AnonymousTypeDisplayInfo GetNormalAnonymousTypeDisplayInfo( ISymbol orderSymbol, IEnumerable<INamedTypeSymbol> directNormalAnonymousTypeReferences, SemanticModel semanticModel, int position); ImmutableArray<SymbolDisplayPart> GetAnonymousTypeParts( INamedTypeSymbol anonymousType, SemanticModel semanticModel, int position); } }
// 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.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.LanguageServices { internal interface IAnonymousTypeDisplayService : ILanguageService { AnonymousTypeDisplayInfo GetNormalAnonymousTypeDisplayInfo( ISymbol orderSymbol, IEnumerable<INamedTypeSymbol> directNormalAnonymousTypeReferences, SemanticModel semanticModel, int position); ImmutableArray<SymbolDisplayPart> GetAnonymousTypeParts( INamedTypeSymbol anonymousType, SemanticModel semanticModel, int position); } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingTypeParameterSymbol.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 Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting ''' <summary> ''' Represents a type parameter in a RetargetingModuleSymbol. Essentially this is a wrapper around ''' another TypeParameterSymbol that is responsible for retargeting symbols from one assembly to another. ''' It can retarget symbols for multiple assemblies at the same time. ''' </summary> Friend NotInheritable Class RetargetingTypeParameterSymbol Inherits SubstitutableTypeParameterSymbol ''' <summary> ''' Owning RetargetingModuleSymbol. ''' </summary> Private ReadOnly _retargetingModule As RetargetingModuleSymbol ''' <summary> ''' The underlying TypeParameterSymbol, cannot be another RetargetingTypeParameterSymbol. ''' </summary> Private ReadOnly _underlyingTypeParameter As TypeParameterSymbol Public Sub New(retargetingModule As RetargetingModuleSymbol, underlyingTypeParameter As TypeParameterSymbol) Debug.Assert(retargetingModule IsNot Nothing) Debug.Assert(underlyingTypeParameter IsNot Nothing) If TypeOf underlyingTypeParameter Is RetargetingTypeParameterSymbol Then Throw New ArgumentException() End If _retargetingModule = retargetingModule _underlyingTypeParameter = underlyingTypeParameter End Sub Private ReadOnly Property RetargetingTranslator As RetargetingModuleSymbol.RetargetingSymbolTranslator Get Return _retargetingModule.RetargetingTranslator End Get End Property Public ReadOnly Property UnderlyingTypeParameter As TypeParameterSymbol Get Return _underlyingTypeParameter End Get End Property Public Overrides ReadOnly Property TypeParameterKind As TypeParameterKind Get Return _underlyingTypeParameter.TypeParameterKind End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return _underlyingTypeParameter.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property Ordinal As Integer Get Return _underlyingTypeParameter.Ordinal End Get End Property Friend Overrides ReadOnly Property ConstraintTypesNoUseSiteDiagnostics As ImmutableArray(Of TypeSymbol) Get Return RetargetingTranslator.Retarget(_underlyingTypeParameter.ConstraintTypesNoUseSiteDiagnostics) End Get End Property Public Overrides ReadOnly Property HasConstructorConstraint As Boolean Get Return _underlyingTypeParameter.HasConstructorConstraint End Get End Property Public Overrides ReadOnly Property HasReferenceTypeConstraint As Boolean Get Return _underlyingTypeParameter.HasReferenceTypeConstraint End Get End Property Public Overrides ReadOnly Property HasValueTypeConstraint As Boolean Get Return _underlyingTypeParameter.HasValueTypeConstraint End Get End Property Public Overrides ReadOnly Property Variance As VarianceKind Get Return _underlyingTypeParameter.Variance End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return RetargetingTranslator.Retarget(_underlyingTypeParameter.ContainingSymbol) End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _underlyingTypeParameter.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return _underlyingTypeParameter.DeclaringSyntaxReferences End Get End Property Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return _underlyingTypeParameter.GetAttributes() End Function Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol Get Return _retargetingModule.ContainingAssembly End Get End Property Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return _retargetingModule End Get End Property Public Overrides ReadOnly Property Name As String Get Return _underlyingTypeParameter.Name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return _underlyingTypeParameter.MetadataName End Get End Property Friend Overrides Sub EnsureAllConstraintsAreResolved() _underlyingTypeParameter.EnsureAllConstraintsAreResolved() End Sub ''' <remarks> ''' This is for perf, not for correctness. ''' </remarks> Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation Get Return Nothing End Get End Property Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return _underlyingTypeParameter.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) 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 Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting ''' <summary> ''' Represents a type parameter in a RetargetingModuleSymbol. Essentially this is a wrapper around ''' another TypeParameterSymbol that is responsible for retargeting symbols from one assembly to another. ''' It can retarget symbols for multiple assemblies at the same time. ''' </summary> Friend NotInheritable Class RetargetingTypeParameterSymbol Inherits SubstitutableTypeParameterSymbol ''' <summary> ''' Owning RetargetingModuleSymbol. ''' </summary> Private ReadOnly _retargetingModule As RetargetingModuleSymbol ''' <summary> ''' The underlying TypeParameterSymbol, cannot be another RetargetingTypeParameterSymbol. ''' </summary> Private ReadOnly _underlyingTypeParameter As TypeParameterSymbol Public Sub New(retargetingModule As RetargetingModuleSymbol, underlyingTypeParameter As TypeParameterSymbol) Debug.Assert(retargetingModule IsNot Nothing) Debug.Assert(underlyingTypeParameter IsNot Nothing) If TypeOf underlyingTypeParameter Is RetargetingTypeParameterSymbol Then Throw New ArgumentException() End If _retargetingModule = retargetingModule _underlyingTypeParameter = underlyingTypeParameter End Sub Private ReadOnly Property RetargetingTranslator As RetargetingModuleSymbol.RetargetingSymbolTranslator Get Return _retargetingModule.RetargetingTranslator End Get End Property Public ReadOnly Property UnderlyingTypeParameter As TypeParameterSymbol Get Return _underlyingTypeParameter End Get End Property Public Overrides ReadOnly Property TypeParameterKind As TypeParameterKind Get Return _underlyingTypeParameter.TypeParameterKind End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return _underlyingTypeParameter.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property Ordinal As Integer Get Return _underlyingTypeParameter.Ordinal End Get End Property Friend Overrides ReadOnly Property ConstraintTypesNoUseSiteDiagnostics As ImmutableArray(Of TypeSymbol) Get Return RetargetingTranslator.Retarget(_underlyingTypeParameter.ConstraintTypesNoUseSiteDiagnostics) End Get End Property Public Overrides ReadOnly Property HasConstructorConstraint As Boolean Get Return _underlyingTypeParameter.HasConstructorConstraint End Get End Property Public Overrides ReadOnly Property HasReferenceTypeConstraint As Boolean Get Return _underlyingTypeParameter.HasReferenceTypeConstraint End Get End Property Public Overrides ReadOnly Property HasValueTypeConstraint As Boolean Get Return _underlyingTypeParameter.HasValueTypeConstraint End Get End Property Public Overrides ReadOnly Property Variance As VarianceKind Get Return _underlyingTypeParameter.Variance End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return RetargetingTranslator.Retarget(_underlyingTypeParameter.ContainingSymbol) End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _underlyingTypeParameter.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return _underlyingTypeParameter.DeclaringSyntaxReferences End Get End Property Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return _underlyingTypeParameter.GetAttributes() End Function Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol Get Return _retargetingModule.ContainingAssembly End Get End Property Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return _retargetingModule End Get End Property Public Overrides ReadOnly Property Name As String Get Return _underlyingTypeParameter.Name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return _underlyingTypeParameter.MetadataName End Get End Property Friend Overrides Sub EnsureAllConstraintsAreResolved() _underlyingTypeParameter.EnsureAllConstraintsAreResolved() End Sub ''' <remarks> ''' This is for perf, not for correctness. ''' </remarks> Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation Get Return Nothing End Get End Property Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return _underlyingTypeParameter.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryParentheses/CSharpRemoveUnnecessaryParenthesesCodeFixProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryParentheses { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryParentheses), Shared] internal class CSharpRemoveUnnecessaryParenthesesCodeFixProvider : AbstractRemoveUnnecessaryParenthesesCodeFixProvider<SyntaxNode> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpRemoveUnnecessaryParenthesesCodeFixProvider() { } protected override bool CanRemoveParentheses(SyntaxNode current, SemanticModel semanticModel, CancellationToken cancellationToken) => current switch { ParenthesizedExpressionSyntax p => CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper(p, semanticModel, cancellationToken, out _, out _), ParenthesizedPatternSyntax p => CSharpRemoveUnnecessaryPatternParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper(p, out _, out _), _ => false, }; } }
// 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryParentheses { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryParentheses), Shared] internal class CSharpRemoveUnnecessaryParenthesesCodeFixProvider : AbstractRemoveUnnecessaryParenthesesCodeFixProvider<SyntaxNode> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpRemoveUnnecessaryParenthesesCodeFixProvider() { } protected override bool CanRemoveParentheses(SyntaxNode current, SemanticModel semanticModel, CancellationToken cancellationToken) => current switch { ParenthesizedExpressionSyntax p => CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper(p, semanticModel, cancellationToken, out _, out _), ParenthesizedPatternSyntax p => CSharpRemoveUnnecessaryPatternParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper(p, out _, out _), _ => false, }; } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/EditorFeatures/Test/SymbolKey/SymbolKeyCrossLanguageTests.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.SymbolKeyTests { [UseExportProvider] public class SymbolKeyCrossLanguageTests { [Theory] [InlineData("dynamic")] [InlineData("int*")] [InlineData("delegate*&lt;int, void&gt;")] public async Task TestUnsupportedVBTypes(string parameterType) { using var workspace = TestWorkspace.Create( @$"<Workspace> <Project Language=""C#"" CommonReferences=""true"" Name=""CSProject""> <Document> public class C {{ public void M({parameterType} d) {{ }} }} </Document> </Project> <Project Language=""Visual Basic"" CommonReference=""true""> <ProjectReference>CSProject</ProjectReference> </Project> </Workspace>"); var solution = workspace.CurrentSolution; var csDocument = solution.Projects.Single(p => p.Language == LanguageNames.CSharp).Documents.Single(); var semanticModel = await csDocument.GetRequiredSemanticModelAsync(CancellationToken.None); var tree = semanticModel.SyntaxTree; var root = tree.GetRoot(); var method = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var methodSymbol = semanticModel.GetDeclaredSymbol(method); var vbProject = solution.Projects.Single(p => p.Language == LanguageNames.VisualBasic); var vbCompilation = await vbProject.GetRequiredCompilationAsync(CancellationToken.None); var resolved = SymbolKey.ResolveString(methodSymbol.GetSymbolKey().ToString(), vbCompilation, out var failureReason, CancellationToken.None); Assert.NotNull(failureReason); Assert.Null(resolved.GetAnySymbol()); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.SymbolKeyTests { [UseExportProvider] public class SymbolKeyCrossLanguageTests { [Theory] [InlineData("dynamic")] [InlineData("int*")] [InlineData("delegate*&lt;int, void&gt;")] public async Task TestUnsupportedVBTypes(string parameterType) { using var workspace = TestWorkspace.Create( @$"<Workspace> <Project Language=""C#"" CommonReferences=""true"" Name=""CSProject""> <Document> public class C {{ public void M({parameterType} d) {{ }} }} </Document> </Project> <Project Language=""Visual Basic"" CommonReference=""true""> <ProjectReference>CSProject</ProjectReference> </Project> </Workspace>"); var solution = workspace.CurrentSolution; var csDocument = solution.Projects.Single(p => p.Language == LanguageNames.CSharp).Documents.Single(); var semanticModel = await csDocument.GetRequiredSemanticModelAsync(CancellationToken.None); var tree = semanticModel.SyntaxTree; var root = tree.GetRoot(); var method = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var methodSymbol = semanticModel.GetDeclaredSymbol(method); var vbProject = solution.Projects.Single(p => p.Language == LanguageNames.VisualBasic); var vbCompilation = await vbProject.GetRequiredCompilationAsync(CancellationToken.None); var resolved = SymbolKey.ResolveString(methodSymbol.GetSymbolKey().ToString(), vbCompilation, out var failureReason, CancellationToken.None); Assert.NotNull(failureReason); Assert.Null(resolved.GetAnySymbol()); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/VisualStudio/Core/Def/EditorConfigSettings/ServiceProviderExtensions.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.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings { internal static class ServiceProviderExtensions { public static bool TryGetService<TService, TInterface>(this IServiceProvider sp, [NotNullWhen(true)] out TInterface? @interface) where TInterface : class { @interface = sp.GetService<TService, TInterface>(throwOnFailure: false); return @interface is not null; } public static bool TryGetService<TInterface>(this IServiceProvider sp, [NotNullWhen(true)] out TInterface? @interface) where TInterface : class { @interface = sp.GetService<TInterface>(); return @interface is not null; } public static TInterface? GetService<TInterface>(this IServiceProvider sp) where TInterface : class { return sp.GetService<TInterface, TInterface>(throwOnFailure: false); } } }
// 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.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings { internal static class ServiceProviderExtensions { public static bool TryGetService<TService, TInterface>(this IServiceProvider sp, [NotNullWhen(true)] out TInterface? @interface) where TInterface : class { @interface = sp.GetService<TService, TInterface>(throwOnFailure: false); return @interface is not null; } public static bool TryGetService<TInterface>(this IServiceProvider sp, [NotNullWhen(true)] out TInterface? @interface) where TInterface : class { @interface = sp.GetService<TInterface>(); return @interface is not null; } public static TInterface? GetService<TInterface>(this IServiceProvider sp) where TInterface : class { return sp.GetService<TInterface, TInterface>(throwOnFailure: false); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Test/Semantic/Compilation/GetSemanticInfoBrokenCodeTests.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 Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class GetSemanticInfoBrokenCodeTests Inherits SemanticModelTestBase <WorkItem(544328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544328")> <Fact> Public Sub Bug12601() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Module M Sub M() Dim x As New { End Sub End Module ]]></file> </compilation>, {SystemCoreRef}) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) VisitAllExpressions(model, tree.GetCompilationUnitRoot()) End Sub <WorkItem(544455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544455")> <Fact> Public Sub EmptyDefaultPropertyName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Class C Default Property End Class Module M Function F(o As C) As Object Return o() End Function End Module ]]></file> </compilation>, {SystemCoreRef}) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) VisitAllExpressions(model, tree.GetCompilationUnitRoot()) End Sub <WorkItem(545233, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545233")> <Fact> Public Sub Bug13538() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Sub M() SyncLock End Sub End Class ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) VisitAllExpressions(model, tree.GetCompilationUnitRoot()) End Sub ''' <summary> ''' The BoundNode tree will contain a BoundPropertyGroup ''' if property overload resolution fails. ''' </summary> <Fact> Public Sub AnalyzePropertyGroup() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Module M Sub M(c As Char, s As String) If c <> s( End Sub End Module ]]></file> </compilation>, {SystemCoreRef}) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) For Each node In GetAllExpressions(tree.GetCompilationUnitRoot()) model.AnalyzeDataFlow(node) Next End Sub <WorkItem(545667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545667")> <Fact()> Public Sub Bug14266() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Enum E A End Enum ]]></file> </compilation>) Dim oldTree = compilation.SyntaxTrees(0) Dim oldText = oldTree.GetText() Dim model = compilation.GetSemanticModel(oldTree) VisitAllDeclarations(model, oldTree.GetCompilationUnitRoot()) ' Insert a single character at the beginning. Dim newText = oldText.Replace(start:=0, length:=0, newText:="B") Dim newTree = oldTree.WithChangedText(newText) compilation = compilation.ReplaceSyntaxTree(oldTree, newTree) model = compilation.GetSemanticModel(newTree) VisitAllDeclarations(model, newTree.GetCompilationUnitRoot()) End Sub <WorkItem(546685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546685")> <Fact()> Public Sub Bug16557() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module M Sub M(b As Boolean) If b Then End If End Sub End Module ]]></file> </compilation>) compilation.AssertNoDiagnostics() ' Change "End Module" to "End module". Dim oldTree = compilation.SyntaxTrees(0) Dim oldText = oldTree.GetText() Dim position = oldText.ToString().LastIndexOf("Module", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="m") Dim newTree = oldTree.WithChangedText(newText) compilation = compilation.ReplaceSyntaxTree(oldTree, newTree) compilation.AssertNoDiagnostics() End Sub <Fact()> Public Sub ExpressionInStructuredTrivia() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ #If e=True ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) For Each expr In GetAllExpressions(tree.GetCompilationUnitRoot()) model.GetTypeInfo(expr) Next End Sub ''' <summary> ''' Me references are not valid within a Module. ''' </summary> <WorkItem(546570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546570")> <Fact()> Public Sub AnalyzeForEachMeInModule() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module M Sub M() For Each Me Next End Sub End Module ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) For Each node In GetAllStatements(tree.GetCompilationUnitRoot()) model.AnalyzeDataFlow(node) Next End Sub <WorkItem(546914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546914")> <Fact()> Public Sub Bug17230_If() AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() If True Then Dim x = Sub() If False : ElseIf End If End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() If True Then Dim x = Sub() If False : Else End If End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() If False End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() If False Then End Sub End Module ]]></file> </compilation>)) End Sub <WorkItem(546914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546914")> <Fact()> Public Sub Bug17230_Other() AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() With False : End With End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() SyncLock False : End SyncLock End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() Select Case False : End Select End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() While False : End While End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() Do While False : Loop End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() For b = True To False : Next End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() For Each b in { False } : Next End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() Using False : End Using End Sub End Module ]]></file> </compilation>)) End Sub <WorkItem(571062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/571062")> <Fact()> Public Sub Bug571062() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class A End Clas 'Class is intentionally misspelled here Namespace N Class B Sub M(Optional o = Nothing) End Sub ReadOnly Property P(Optional o = Nothing) Get Return Nothing End Get End Property Event E(Optional o = Nothing) Private F = Function(Optional o = Nothing) Nothing Delegate Sub D(Optional o = Nothing) End Class End Namespace ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) VisitAllExpressions(model, tree.GetCompilationUnitRoot()) End Sub <WorkItem(578141, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578141")> <Fact()> Public Sub IsImplicitlyDeclared() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Dim F MustOverride Property P MustOverride Sub M() ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim diagnostics = model.GetDiagnostics().ToArray() Assert.NotEmpty(diagnostics) Dim type = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)(TypeSymbol.ImplicitTypeName) Assert.True(type.IsImplicitlyDeclared) Dim member As Symbol member = type.GetMember(Of FieldSymbol)("F") Assert.False(member.IsImplicitlyDeclared) member = type.GetMember(Of PropertySymbol)("P") Assert.False(member.IsImplicitlyDeclared) member = type.GetMember(Of MethodSymbol)("M") Assert.False(member.IsImplicitlyDeclared) End Sub <WorkItem(578141, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578141")> <ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40682: The test hook is blocked by this issue. <WorkItem(40682, "https://github.com/dotnet/roslyn/issues/40682")> Public Sub MustOverrideMember() ' MustOverride method in script class. MustOverrideMemberCore(CompilationUtils.CreateCompilationWithMscorlib40({VisualBasicSyntaxTree.ParseText(<![CDATA[ MustOverride Sub M() ]]>.Value, options:=TestOptions.Script)})) ' MustOverride method in invalid class. MustOverrideMemberCore(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ MClass C MustOverride Sub M() End Class ]]></file> </compilation>)) ' MustOverride property in script class. MustOverrideMemberCore(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ MClass C MustOverride Property P End Class ]]></file> </compilation>)) ' MustOverride constructor. MustOverrideMemberCore(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ MustInherit Class C MustOverride Sub New() End Class ]]></file> </compilation>)) ' MustOverride method in class not MustInherit MustOverrideMemberCore(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C MustOverride Sub M() End Class ]]></file> </compilation>)) End Sub Private Sub MustOverrideMemberCore(compilation As VisualBasicCompilation) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim diagnostics = model.GetDiagnostics().ToArray() Assert.NotEmpty(diagnostics) End Sub <WorkItem(611707, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611707")> <Fact()> Public Sub UnexpectedVarianceKeyword() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface(Await ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim diagnostics = model.GetDiagnostics().ToArray() Assert.NotEmpty(diagnostics) End Sub <WorkItem(611707, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611707")> <Fact()> Public Sub UnexpectedVarianceKeyword_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Delegate Sub D(Of From ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim diagnostics = model.GetDiagnostics().ToArray() Assert.NotEmpty(diagnostics) End Sub <WorkItem(762034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762034")> <Fact()> Public Sub Bug762034() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Dim t = !Str ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) For Each expr In GetAllExpressions(tree.GetCompilationUnitRoot()) Dim symbolInfo = model.GetSymbolInfo(expr) Assert.NotNull(symbolInfo) model.AnalyzeDataFlow(expr) Next End Sub Private Sub AnalyzeExpressionDataFlow(compilation As VisualBasicCompilation) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) For Each expr In GetAllExpressions(tree.GetCompilationUnitRoot()) model.AnalyzeDataFlow(expr) Next End Sub Private Sub VisitAllExpressions(model As SemanticModel, node As VisualBasicSyntaxNode) For Each expr In GetAllExpressions(node) Dim symbolInfo = model.GetSymbolInfo(expr) Assert.NotNull(symbolInfo) Dim typeInfo = model.GetTypeInfo(expr) Assert.NotNull(typeInfo) Next End Sub Private Sub VisitAllDeclarations(model As SemanticModel, node As VisualBasicSyntaxNode) For Each node In node.DescendantNodesAndSelf() model.GetDeclaredSymbol(node) Next End Sub Private Shared Function GetAllExpressions(node As VisualBasicSyntaxNode) As IEnumerable(Of ExpressionSyntax) Return node.DescendantNodesAndSelf(descendIntoTrivia:=True).OfType(Of ExpressionSyntax)() End Function Private Shared Function GetAllStatements(node As VisualBasicSyntaxNode) As IEnumerable(Of ExecutableStatementSyntax) Return node.DescendantNodesAndSelf().OfType(Of ExecutableStatementSyntax)() 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 Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class GetSemanticInfoBrokenCodeTests Inherits SemanticModelTestBase <WorkItem(544328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544328")> <Fact> Public Sub Bug12601() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Module M Sub M() Dim x As New { End Sub End Module ]]></file> </compilation>, {SystemCoreRef}) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) VisitAllExpressions(model, tree.GetCompilationUnitRoot()) End Sub <WorkItem(544455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544455")> <Fact> Public Sub EmptyDefaultPropertyName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Class C Default Property End Class Module M Function F(o As C) As Object Return o() End Function End Module ]]></file> </compilation>, {SystemCoreRef}) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) VisitAllExpressions(model, tree.GetCompilationUnitRoot()) End Sub <WorkItem(545233, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545233")> <Fact> Public Sub Bug13538() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C Sub M() SyncLock End Sub End Class ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) VisitAllExpressions(model, tree.GetCompilationUnitRoot()) End Sub ''' <summary> ''' The BoundNode tree will contain a BoundPropertyGroup ''' if property overload resolution fails. ''' </summary> <Fact> Public Sub AnalyzePropertyGroup() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Module M Sub M(c As Char, s As String) If c <> s( End Sub End Module ]]></file> </compilation>, {SystemCoreRef}) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) For Each node In GetAllExpressions(tree.GetCompilationUnitRoot()) model.AnalyzeDataFlow(node) Next End Sub <WorkItem(545667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545667")> <Fact()> Public Sub Bug14266() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Enum E A End Enum ]]></file> </compilation>) Dim oldTree = compilation.SyntaxTrees(0) Dim oldText = oldTree.GetText() Dim model = compilation.GetSemanticModel(oldTree) VisitAllDeclarations(model, oldTree.GetCompilationUnitRoot()) ' Insert a single character at the beginning. Dim newText = oldText.Replace(start:=0, length:=0, newText:="B") Dim newTree = oldTree.WithChangedText(newText) compilation = compilation.ReplaceSyntaxTree(oldTree, newTree) model = compilation.GetSemanticModel(newTree) VisitAllDeclarations(model, newTree.GetCompilationUnitRoot()) End Sub <WorkItem(546685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546685")> <Fact()> Public Sub Bug16557() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module M Sub M(b As Boolean) If b Then End If End Sub End Module ]]></file> </compilation>) compilation.AssertNoDiagnostics() ' Change "End Module" to "End module". Dim oldTree = compilation.SyntaxTrees(0) Dim oldText = oldTree.GetText() Dim position = oldText.ToString().LastIndexOf("Module", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="m") Dim newTree = oldTree.WithChangedText(newText) compilation = compilation.ReplaceSyntaxTree(oldTree, newTree) compilation.AssertNoDiagnostics() End Sub <Fact()> Public Sub ExpressionInStructuredTrivia() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ #If e=True ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) For Each expr In GetAllExpressions(tree.GetCompilationUnitRoot()) model.GetTypeInfo(expr) Next End Sub ''' <summary> ''' Me references are not valid within a Module. ''' </summary> <WorkItem(546570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546570")> <Fact()> Public Sub AnalyzeForEachMeInModule() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module M Sub M() For Each Me Next End Sub End Module ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) For Each node In GetAllStatements(tree.GetCompilationUnitRoot()) model.AnalyzeDataFlow(node) Next End Sub <WorkItem(546914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546914")> <Fact()> Public Sub Bug17230_If() AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() If True Then Dim x = Sub() If False : ElseIf End If End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() If True Then Dim x = Sub() If False : Else End If End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() If False End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() If False Then End Sub End Module ]]></file> </compilation>)) End Sub <WorkItem(546914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546914")> <Fact()> Public Sub Bug17230_Other() AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() With False : End With End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() SyncLock False : End SyncLock End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() Select Case False : End Select End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() While False : End While End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() Do While False : Loop End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() For b = True To False : Next End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() For Each b in { False } : Next End Sub End Module ]]></file> </compilation>)) AnalyzeExpressionDataFlow(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() Dim x = Sub() Using False : End Using End Sub End Module ]]></file> </compilation>)) End Sub <WorkItem(571062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/571062")> <Fact()> Public Sub Bug571062() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class A End Clas 'Class is intentionally misspelled here Namespace N Class B Sub M(Optional o = Nothing) End Sub ReadOnly Property P(Optional o = Nothing) Get Return Nothing End Get End Property Event E(Optional o = Nothing) Private F = Function(Optional o = Nothing) Nothing Delegate Sub D(Optional o = Nothing) End Class End Namespace ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) VisitAllExpressions(model, tree.GetCompilationUnitRoot()) End Sub <WorkItem(578141, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578141")> <Fact()> Public Sub IsImplicitlyDeclared() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Dim F MustOverride Property P MustOverride Sub M() ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim diagnostics = model.GetDiagnostics().ToArray() Assert.NotEmpty(diagnostics) Dim type = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)(TypeSymbol.ImplicitTypeName) Assert.True(type.IsImplicitlyDeclared) Dim member As Symbol member = type.GetMember(Of FieldSymbol)("F") Assert.False(member.IsImplicitlyDeclared) member = type.GetMember(Of PropertySymbol)("P") Assert.False(member.IsImplicitlyDeclared) member = type.GetMember(Of MethodSymbol)("M") Assert.False(member.IsImplicitlyDeclared) End Sub <WorkItem(578141, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578141")> <ConditionalFact(GetType(NoUsedAssembliesValidation))> ' https://github.com/dotnet/roslyn/issues/40682: The test hook is blocked by this issue. <WorkItem(40682, "https://github.com/dotnet/roslyn/issues/40682")> Public Sub MustOverrideMember() ' MustOverride method in script class. MustOverrideMemberCore(CompilationUtils.CreateCompilationWithMscorlib40({VisualBasicSyntaxTree.ParseText(<![CDATA[ MustOverride Sub M() ]]>.Value, options:=TestOptions.Script)})) ' MustOverride method in invalid class. MustOverrideMemberCore(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ MClass C MustOverride Sub M() End Class ]]></file> </compilation>)) ' MustOverride property in script class. MustOverrideMemberCore(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ MClass C MustOverride Property P End Class ]]></file> </compilation>)) ' MustOverride constructor. MustOverrideMemberCore(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ MustInherit Class C MustOverride Sub New() End Class ]]></file> </compilation>)) ' MustOverride method in class not MustInherit MustOverrideMemberCore(CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Class C MustOverride Sub M() End Class ]]></file> </compilation>)) End Sub Private Sub MustOverrideMemberCore(compilation As VisualBasicCompilation) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim diagnostics = model.GetDiagnostics().ToArray() Assert.NotEmpty(diagnostics) End Sub <WorkItem(611707, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611707")> <Fact()> Public Sub UnexpectedVarianceKeyword() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface(Await ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim diagnostics = model.GetDiagnostics().ToArray() Assert.NotEmpty(diagnostics) End Sub <WorkItem(611707, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611707")> <Fact()> Public Sub UnexpectedVarianceKeyword_2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Delegate Sub D(Of From ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim diagnostics = model.GetDiagnostics().ToArray() Assert.NotEmpty(diagnostics) End Sub <WorkItem(762034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762034")> <Fact()> Public Sub Bug762034() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Dim t = !Str ]]></file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) For Each expr In GetAllExpressions(tree.GetCompilationUnitRoot()) Dim symbolInfo = model.GetSymbolInfo(expr) Assert.NotNull(symbolInfo) model.AnalyzeDataFlow(expr) Next End Sub Private Sub AnalyzeExpressionDataFlow(compilation As VisualBasicCompilation) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) For Each expr In GetAllExpressions(tree.GetCompilationUnitRoot()) model.AnalyzeDataFlow(expr) Next End Sub Private Sub VisitAllExpressions(model As SemanticModel, node As VisualBasicSyntaxNode) For Each expr In GetAllExpressions(node) Dim symbolInfo = model.GetSymbolInfo(expr) Assert.NotNull(symbolInfo) Dim typeInfo = model.GetTypeInfo(expr) Assert.NotNull(typeInfo) Next End Sub Private Sub VisitAllDeclarations(model As SemanticModel, node As VisualBasicSyntaxNode) For Each node In node.DescendantNodesAndSelf() model.GetDeclaredSymbol(node) Next End Sub Private Shared Function GetAllExpressions(node As VisualBasicSyntaxNode) As IEnumerable(Of ExpressionSyntax) Return node.DescendantNodesAndSelf(descendIntoTrivia:=True).OfType(Of ExpressionSyntax)() End Function Private Shared Function GetAllStatements(node As VisualBasicSyntaxNode) As IEnumerable(Of ExecutableStatementSyntax) Return node.DescendantNodesAndSelf().OfType(Of ExecutableStatementSyntax)() End Function End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/EditorFeatures/Core/InheritanceMargin/AbstractInheritanceMarginService.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.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolMapping; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.InheritanceMargin.InheritanceMarginServiceHelper; namespace Microsoft.CodeAnalysis.InheritanceMargin { internal abstract class AbstractInheritanceMarginService : IInheritanceMarginService { /// <summary> /// Given the syntax nodes to search, /// get all the method, event, property and type declaration syntax nodes. /// </summary> protected abstract ImmutableArray<SyntaxNode> GetMembers(IEnumerable<SyntaxNode> nodesToSearch); /// <summary> /// Get the token that represents declaration node. /// e.g. Identifier for method/property/event and this keyword for indexer. /// </summary> protected abstract SyntaxToken GetDeclarationToken(SyntaxNode declarationNode); public async ValueTask<ImmutableArray<InheritanceMarginItem>> GetInheritanceMemberItemsAsync( Document document, TextSpan spanToSearch, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var allDeclarationNodes = GetMembers(root.DescendantNodes(spanToSearch)); if (allDeclarationNodes.IsEmpty) { return ImmutableArray<InheritanceMarginItem>.Empty; } var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var mappingService = document.Project.Solution.Workspace.Services.GetRequiredService<ISymbolMappingService>(); using var _ = ArrayBuilder<(SymbolKey symbolKey, int lineNumber)>.GetInstance(out var builder); Project? project = null; foreach (var memberDeclarationNode in allDeclarationNodes) { var member = semanticModel.GetDeclaredSymbol(memberDeclarationNode, cancellationToken); if (member == null || !CanHaveInheritanceTarget(member)) { continue; } // Use mapping service to find correct solution & symbol. (e.g. metadata symbol) var mappingResult = await mappingService.MapSymbolAsync(document, member, cancellationToken).ConfigureAwait(false); if (mappingResult == null) { continue; } // All the symbols here are declared in the same document, they should belong to the same project. // So here it is enough to get the project once. project ??= mappingResult.Project; builder.Add((mappingResult.Symbol.GetSymbolKey(cancellationToken), sourceText.Lines.GetLineFromPosition(GetDeclarationToken(memberDeclarationNode).SpanStart).LineNumber)); } var symbolKeyAndLineNumbers = builder.ToImmutable(); if (symbolKeyAndLineNumbers.IsEmpty || project == null) { return ImmutableArray<InheritanceMarginItem>.Empty; } var solution = project.Solution; var serializedInheritanceMarginItems = await GetInheritanceMemberItemAsync( solution, project.Id, symbolKeyAndLineNumbers, cancellationToken).ConfigureAwait(false); return await serializedInheritanceMarginItems.SelectAsArrayAsync( (serializedItem, _) => InheritanceMarginItem.ConvertAsync(solution, serializedItem, cancellationToken), cancellationToken).ConfigureAwait(false); } private static bool CanHaveInheritanceTarget(ISymbol symbol) { if (symbol is INamedTypeSymbol namedType) { return !symbol.IsStatic && namedType.TypeKind is TypeKind.Interface or TypeKind.Class or TypeKind.Struct; } if (symbol is IEventSymbol or IPropertySymbol or IMethodSymbol { MethodKind: MethodKind.Ordinary or MethodKind.ExplicitInterfaceImplementation or MethodKind.UserDefinedOperator or MethodKind.Conversion }) { return true; } return false; } } }
// 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.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolMapping; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.InheritanceMargin.InheritanceMarginServiceHelper; namespace Microsoft.CodeAnalysis.InheritanceMargin { internal abstract class AbstractInheritanceMarginService : IInheritanceMarginService { /// <summary> /// Given the syntax nodes to search, /// get all the method, event, property and type declaration syntax nodes. /// </summary> protected abstract ImmutableArray<SyntaxNode> GetMembers(IEnumerable<SyntaxNode> nodesToSearch); /// <summary> /// Get the token that represents declaration node. /// e.g. Identifier for method/property/event and this keyword for indexer. /// </summary> protected abstract SyntaxToken GetDeclarationToken(SyntaxNode declarationNode); public async ValueTask<ImmutableArray<InheritanceMarginItem>> GetInheritanceMemberItemsAsync( Document document, TextSpan spanToSearch, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var allDeclarationNodes = GetMembers(root.DescendantNodes(spanToSearch)); if (allDeclarationNodes.IsEmpty) { return ImmutableArray<InheritanceMarginItem>.Empty; } var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var mappingService = document.Project.Solution.Workspace.Services.GetRequiredService<ISymbolMappingService>(); using var _ = ArrayBuilder<(SymbolKey symbolKey, int lineNumber)>.GetInstance(out var builder); Project? project = null; foreach (var memberDeclarationNode in allDeclarationNodes) { var member = semanticModel.GetDeclaredSymbol(memberDeclarationNode, cancellationToken); if (member == null || !CanHaveInheritanceTarget(member)) { continue; } // Use mapping service to find correct solution & symbol. (e.g. metadata symbol) var mappingResult = await mappingService.MapSymbolAsync(document, member, cancellationToken).ConfigureAwait(false); if (mappingResult == null) { continue; } // All the symbols here are declared in the same document, they should belong to the same project. // So here it is enough to get the project once. project ??= mappingResult.Project; builder.Add((mappingResult.Symbol.GetSymbolKey(cancellationToken), sourceText.Lines.GetLineFromPosition(GetDeclarationToken(memberDeclarationNode).SpanStart).LineNumber)); } var symbolKeyAndLineNumbers = builder.ToImmutable(); if (symbolKeyAndLineNumbers.IsEmpty || project == null) { return ImmutableArray<InheritanceMarginItem>.Empty; } var solution = project.Solution; var serializedInheritanceMarginItems = await GetInheritanceMemberItemAsync( solution, project.Id, symbolKeyAndLineNumbers, cancellationToken).ConfigureAwait(false); return await serializedInheritanceMarginItems.SelectAsArrayAsync( (serializedItem, _) => InheritanceMarginItem.ConvertAsync(solution, serializedItem, cancellationToken), cancellationToken).ConfigureAwait(false); } private static bool CanHaveInheritanceTarget(ISymbol symbol) { if (symbol is INamedTypeSymbol namedType) { return !symbol.IsStatic && namedType.TypeKind is TypeKind.Interface or TypeKind.Class or TypeKind.Struct; } if (symbol is IEventSymbol or IPropertySymbol or IMethodSymbol { MethodKind: MethodKind.Ordinary or MethodKind.ExplicitInterfaceImplementation or MethodKind.UserDefinedOperator or MethodKind.Conversion }) { return true; } return false; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/EditorFeatures/VisualBasic/AutomaticCompletion/VisualBasicBraceCompletions.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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticCompletion Friend Module VisualBasicBraceCompletions End Module 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticCompletion Friend Module VisualBasicBraceCompletions End Module End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Workspaces/Core/Portable/Storage/SQLite/Interop/SafeSqliteHandle.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.Runtime.InteropServices; using Microsoft.CodeAnalysis.Shared.Extensions; using SQLitePCL; namespace Microsoft.CodeAnalysis.SQLite.Interop { internal sealed class SafeSqliteHandle : SafeHandle { private readonly sqlite3? _wrapper; private readonly SafeHandleLease _lease; public SafeSqliteHandle(sqlite3? wrapper) : base(invalidHandleValue: IntPtr.Zero, ownsHandle: true) { _wrapper = wrapper; if (wrapper is not null) { _lease = wrapper.Lease(); SetHandle(wrapper.DangerousGetHandle()); } else { _lease = default; SetHandle(IntPtr.Zero); } } public override bool IsInvalid => handle == IntPtr.Zero; public sqlite3 DangerousGetWrapper() => _wrapper!; protected override bool ReleaseHandle() { using var _ = _wrapper; _lease.Dispose(); SetHandle(IntPtr.Zero); 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.Runtime.InteropServices; using Microsoft.CodeAnalysis.Shared.Extensions; using SQLitePCL; namespace Microsoft.CodeAnalysis.SQLite.Interop { internal sealed class SafeSqliteHandle : SafeHandle { private readonly sqlite3? _wrapper; private readonly SafeHandleLease _lease; public SafeSqliteHandle(sqlite3? wrapper) : base(invalidHandleValue: IntPtr.Zero, ownsHandle: true) { _wrapper = wrapper; if (wrapper is not null) { _lease = wrapper.Lease(); SetHandle(wrapper.DangerousGetHandle()); } else { _lease = default; SetHandle(IntPtr.Zero); } } public override bool IsInvalid => handle == IntPtr.Zero; public sqlite3 DangerousGetWrapper() => _wrapper!; protected override bool ReleaseHandle() { using var _ = _wrapper; _lease.Dispose(); SetHandle(IntPtr.Zero); return true; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Tools/ExternalAccess/FSharp/PublicAPI.Shipped.txt
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Analyzers/Core/CodeFixes/xlf/CodeFixesResources.ja.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="ja" original="../CodeFixesResources.resx"> <body> <trans-unit id="Add_blank_line_after_block"> <source>Add blank line after block</source> <target state="translated">ブロックの後に空白行を追加する</target> <note /> </trans-unit> <trans-unit id="Add_both"> <source>Add both</source> <target state="translated">両方を追加する</target> <note /> </trans-unit> <trans-unit id="Add_default_case"> <source>Add default case</source> <target state="translated">既定のケースの追加</target> <note /> </trans-unit> <trans-unit id="Add_file_header"> <source>Add file header</source> <target state="translated">ファイル ヘッダーの追加</target> <note /> </trans-unit> <trans-unit id="Fix_Name_Violation_colon_0"> <source>Fix Name Violation: {0}</source> <target state="translated">名前の違反を修正します: {0}</target> <note /> </trans-unit> <trans-unit id="Fix_all_occurrences_in"> <source>Fix all occurrences in</source> <target state="translated">次の場所のすべての出現箇所を修正します</target> <note /> </trans-unit> <trans-unit id="Remove_extra_blank_lines"> <source>Remove extra blank lines</source> <target state="translated">余分な空白行を削除する</target> <note /> </trans-unit> <trans-unit id="Remove_redundant_assignment"> <source>Remove redundant assignment</source> <target state="translated">冗長な代入を削除します</target> <note /> </trans-unit> <trans-unit id="Suppress_or_Configure_issues"> <source>Suppress or Configure issues</source> <target state="translated">問題の抑制または構成</target> <note /> </trans-unit> <trans-unit id="Update_suppression_format"> <source>Update suppression format</source> <target state="translated">抑制の形式の更新</target> <note /> </trans-unit> <trans-unit id="Use_discard_underscore"> <source>Use discard '_'</source> <target state="translated">破棄 '_' を使用</target> <note /> </trans-unit> <trans-unit id="Use_discarded_local"> <source>Use discarded local</source> <target state="translated">破棄されたローカルを使用します</target> <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="ja" original="../CodeFixesResources.resx"> <body> <trans-unit id="Add_blank_line_after_block"> <source>Add blank line after block</source> <target state="translated">ブロックの後に空白行を追加する</target> <note /> </trans-unit> <trans-unit id="Add_both"> <source>Add both</source> <target state="translated">両方を追加する</target> <note /> </trans-unit> <trans-unit id="Add_default_case"> <source>Add default case</source> <target state="translated">既定のケースの追加</target> <note /> </trans-unit> <trans-unit id="Add_file_header"> <source>Add file header</source> <target state="translated">ファイル ヘッダーの追加</target> <note /> </trans-unit> <trans-unit id="Fix_Name_Violation_colon_0"> <source>Fix Name Violation: {0}</source> <target state="translated">名前の違反を修正します: {0}</target> <note /> </trans-unit> <trans-unit id="Fix_all_occurrences_in"> <source>Fix all occurrences in</source> <target state="translated">次の場所のすべての出現箇所を修正します</target> <note /> </trans-unit> <trans-unit id="Remove_extra_blank_lines"> <source>Remove extra blank lines</source> <target state="translated">余分な空白行を削除する</target> <note /> </trans-unit> <trans-unit id="Remove_redundant_assignment"> <source>Remove redundant assignment</source> <target state="translated">冗長な代入を削除します</target> <note /> </trans-unit> <trans-unit id="Suppress_or_Configure_issues"> <source>Suppress or Configure issues</source> <target state="translated">問題の抑制または構成</target> <note /> </trans-unit> <trans-unit id="Update_suppression_format"> <source>Update suppression format</source> <target state="translated">抑制の形式の更新</target> <note /> </trans-unit> <trans-unit id="Use_discard_underscore"> <source>Use discard '_'</source> <target state="translated">破棄 '_' を使用</target> <note /> </trans-unit> <trans-unit id="Use_discarded_local"> <source>Use discarded local</source> <target state="translated">破棄されたローカルを使用します</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Workspaces/Remote/Core/ExternalAccess/UnitTesting/Api/UnitTestingRemoteServiceCallbackDispatcher.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 Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal abstract class UnitTestingRemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher { private readonly RemoteServiceCallbackDispatcher _dispatcher = new(); public object GetCallback(UnitTestingRemoteServiceCallbackIdWrapper callbackId) => _dispatcher.GetCallback(callbackId.UnderlyingObject); RemoteServiceCallbackDispatcher.Handle IRemoteServiceCallbackDispatcher.CreateHandle(object? instance) => _dispatcher.CreateHandle(instance); } }
// 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 Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal abstract class UnitTestingRemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher { private readonly RemoteServiceCallbackDispatcher _dispatcher = new(); public object GetCallback(UnitTestingRemoteServiceCallbackIdWrapper callbackId) => _dispatcher.GetCallback(callbackId.UnderlyingObject); RemoteServiceCallbackDispatcher.Handle IRemoteServiceCallbackDispatcher.CreateHandle(object? instance) => _dispatcher.CreateHandle(instance); } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_Locations.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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Locations : CSharpTestBase { [Fact] public void Global1() { var source1 = @" [assembly: A] [module: A] "; var source2 = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CreateCompilation(new[] { source1, source2 }).VerifyDiagnostics(); } [Fact] public void Global2() { var source1 = @" namespace N { [assembly: A] } "; var source2 = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CreateCompilation(new[] { source1, source2 }).VerifyDiagnostics( // (4,6): error CS1730: Assembly and module attributes must precede all other elements defined in a file except using clauses and extern alias declarations Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "assembly")); } [Fact] public void Global3() { var source1 = @" class X { [A] } "; var source2 = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CreateCompilation(new[] { source1, source2 }).VerifyDiagnostics( // (5,1): error CS1519: Unexpected token '}', member declaration expected. Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "}").WithArguments("}")); } [Fact] public void OnClass() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] class C { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnStruct() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] struct S { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnRecordStruct() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] record struct S { } "; CreateCompilation(source, parseOptions: TestOptions.Regular10).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnRecordClass() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] record class S { } "; CreateCompilation(source, parseOptions: TestOptions.Regular10).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnEnum() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] enum E { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnInterface() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] interface I { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnDelegate() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] delegate void D(int a); "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type, return"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type, return"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type, return"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type, return"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type, return"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type, return"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type, return"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type, return"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type, return")); } [Fact] public void OnMethod() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] void M(int a) { } } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, return"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, return"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, return"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, return"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, return"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, return"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, return"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, return")); } [Fact] public void OnField() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int a; } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "field"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "field"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "field"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "field"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "field"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "field"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "field"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "field"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "field"), // (21,9): warning CS0169: The field 'C.a' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("C.a")); } [Fact] public void OnEnumField() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } enum E { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] x } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "field"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "field"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "field"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "field"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "field"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "field"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "field"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "field"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "field")); } [Fact] public void OnProperty() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int a { get; set; } } "; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "field, property").WithLocation(10, 6), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "field, property").WithLocation(11, 6), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "field, property").WithLocation(12, 6), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field, property").WithLocation(13, 6), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "field, property").WithLocation(16, 6), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "field, property").WithLocation(17, 6), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "field, property").WithLocation(18, 6), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "field, property").WithLocation(19, 6), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "field, property").WithLocation(20, 6)); } [Fact] public void OnPropertyGetter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { int Goo { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] get { return 0; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, return"), // (13,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, return"), // (14,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, return"), // (16,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return"), // (17,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, return"), // (18,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, return"), // (20,10): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, return"), // (21,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, return"), // (22,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, return")); } [Fact] public void OnPropertySetter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { int Goo { get { return 0; } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (14,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, param, return"), // (15,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, param, return"), // (16,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, param, return"), // (18,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, param, return"), // (19,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, param, return"), // (20,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, param, return"), // (23,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, param, return"), // (24,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, param, return")); } [Fact] public void OnFieldEvent() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] event System.Action e; } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, field, event"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, field, event"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, field, event"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, field, event"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "method, field, event"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, field, event"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, field, event"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, field, event"), // (21,25): warning CS0067: The event 'C.e' is never used Diagnostic(ErrorCode.WRN_UnreferencedEvent, "e").WithArguments("C.e")); } [Fact, WorkItem(543977, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543977")] public void OnInterfaceFieldEvent() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } interface I { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] event System.Action e; } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, event"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, event"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, event"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, event"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, event"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "method, event"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, event"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, event"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, event")); } [Fact] public void OnCustomEvent() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] event Action E { add { } remove { } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "event"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "event"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "event"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "event"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "event"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "event"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "event"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "event"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "event"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "event")); } [Fact] public void OnEventAdder() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { event Action Goo { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] add { } remove { } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, param, return"), // (13,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, param, return"), // (14,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, param, return"), // (16,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, param, return"), // (17,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, param, return"), // (18,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, param, return"), // (21,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, param, return"), // (22,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, param, return")); } [Fact] public void OnEventRemover() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { event Action Goo { add { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] remove { } } } "; CreateCompilation(source).VerifyDiagnostics( // (14,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, param, return"), // (15,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, param, return"), // (16,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, param, return"), // (18,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, param, return"), // (19,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, param, return"), // (20,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, param, return"), // (23,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, param, return"), // (24,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, param, return")); } [Fact] public void OnTypeParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C < [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] T > { } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "typevar"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "typevar"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "typevar"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "typevar"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "typevar"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "typevar"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "typevar"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "typevar"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "typevar"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "typevar")); } [Fact] public void OnMethodParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { void f( [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int x ) { } } "; CreateCompilation(source).VerifyDiagnostics( // (11,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "param"), // (12,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "param"), // (13,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "param"), // (14,10): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "param"), // (15,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param"), // (16,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param"), // (17,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "param"), // (18,10): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "param"), // (20,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "param"), // (21,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "param")); } [Fact] public void OnDelegateParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } delegate void D( [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int x ); "; CreateCompilation(source).VerifyDiagnostics( // (9,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "param"), // (10,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "param"), // (11,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "param"), // (12,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "param"), // (13,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param"), // (14,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param"), // (15,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "param"), // (16,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "param"), // (18,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "param"), // (19,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "param")); } [Fact] public void OnIndexerParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { int this[ [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int x] { get { return 0; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (11,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "param"), // (12,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "param"), // (13,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "param"), // (14,10): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "param"), // (15,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param"), // (16,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param"), // (17,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "param"), // (18,10): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "param"), // (20,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "param"), // (21,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "param")); } [Fact] public void UnrecognizedLocations() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [class: A] [struct: A] [interface: A] [delegate: A] [enum: A] [add: A] [remove: A] [get: A] [set: A] class C { }"; CreateCompilation(source).VerifyDiagnostics( // (7,2): warning CS0658: 'class' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "class").WithArguments("class", "type"), // (8,2): warning CS0658: 'struct' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "struct").WithArguments("struct", "type"), // (9,2): warning CS0658: 'interface' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "interface").WithArguments("interface", "type"), // (10,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type"), // (11,2): warning CS0658: 'enum' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "enum").WithArguments("enum", "type"), // (12,2): warning CS0658: 'add' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "add").WithArguments("add", "type"), // (13,2): warning CS0658: 'remove' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "remove").WithArguments("remove", "type"), // (14,2): warning CS0658: 'get' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "get").WithArguments("get", "type"), // (15,2): warning CS0658: 'set' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "set").WithArguments("set", "type")); } [Fact, WorkItem(545555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545555")] public void AttributesWithInvalidLocationNotEmitted() { var source = @" using System; public class goo { public static void Main() { object[] o = typeof(goo).GetMethod(""Boo"").GetCustomAttributes(typeof(A), false); Console.WriteLine(""Attribute Count={0}"", o.Length); } [goo: A] [method: A] public int Boo(int i) { return 1; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CompileAndVerify(source, expectedOutput: "Attribute Count=1").VerifyDiagnostics( // (12,6): warning CS0658: 'goo' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "goo").WithArguments("goo", "method, return")); } [WorkItem(537613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537613"), WorkItem(537738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537738")] [Fact] public void CS0246ERR_SingleTypeNameNotFound_VerbatimIdentifierAttributeTarget() { CreateCompilation(@"class A { [@return:X] void B() { } }").VerifyDiagnostics( // (1,20): error CS0246: The type or namespace name 'XAttribute' could not be found (are you missing a using directive or an assembly reference?) // class A { [@return:X] void B() { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("XAttribute").WithLocation(1, 20), // (1,20): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // class A { [@return:X] void B() { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(1, 20)); } [WorkItem(537613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537613"), WorkItem(537738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537738")] [Fact] public void CS0246ERR_SingleTypeNameNotFound_VerbatimIdentifierAttributeTargetAndAttribute() { var source = @" using System; class X: Attribute {} class XAttribute: Attribute {} class A { [return:X] void M() { } } // Ambiguous class B { [@return:X] void M() { } } // Ambiguous class C { [return:@X] void M() { } } // Fine, binds to X class D { [@return:@X] void M() { } } // Fine, binds to X "; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute' // class A { [return:X] void M() { } } // Ambiguous Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "X").WithArguments("X", "X", "XAttribute"), // (8,20): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute' // class B { [@return:X] void M() { } } // Ambiguous Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "X").WithArguments("X", "X", "XAttribute")); } } }
// 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Locations : CSharpTestBase { [Fact] public void Global1() { var source1 = @" [assembly: A] [module: A] "; var source2 = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CreateCompilation(new[] { source1, source2 }).VerifyDiagnostics(); } [Fact] public void Global2() { var source1 = @" namespace N { [assembly: A] } "; var source2 = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CreateCompilation(new[] { source1, source2 }).VerifyDiagnostics( // (4,6): error CS1730: Assembly and module attributes must precede all other elements defined in a file except using clauses and extern alias declarations Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "assembly")); } [Fact] public void Global3() { var source1 = @" class X { [A] } "; var source2 = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CreateCompilation(new[] { source1, source2 }).VerifyDiagnostics( // (5,1): error CS1519: Unexpected token '}', member declaration expected. Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "}").WithArguments("}")); } [Fact] public void OnClass() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] class C { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnStruct() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] struct S { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnRecordStruct() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] record struct S { } "; CreateCompilation(source, parseOptions: TestOptions.Regular10).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnRecordClass() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] record class S { } "; CreateCompilation(source, parseOptions: TestOptions.Regular10).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnEnum() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] enum E { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnInterface() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] interface I { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnDelegate() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] delegate void D(int a); "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type, return"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type, return"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type, return"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type, return"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type, return"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type, return"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type, return"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type, return"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type, return")); } [Fact] public void OnMethod() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] void M(int a) { } } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, return"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, return"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, return"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, return"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, return"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, return"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, return"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, return")); } [Fact] public void OnField() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int a; } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "field"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "field"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "field"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "field"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "field"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "field"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "field"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "field"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "field"), // (21,9): warning CS0169: The field 'C.a' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("C.a")); } [Fact] public void OnEnumField() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } enum E { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] x } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "field"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "field"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "field"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "field"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "field"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "field"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "field"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "field"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "field")); } [Fact] public void OnProperty() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int a { get; set; } } "; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "field, property").WithLocation(10, 6), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "field, property").WithLocation(11, 6), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "field, property").WithLocation(12, 6), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field, property").WithLocation(13, 6), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "field, property").WithLocation(16, 6), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "field, property").WithLocation(17, 6), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "field, property").WithLocation(18, 6), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "field, property").WithLocation(19, 6), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "field, property").WithLocation(20, 6)); } [Fact] public void OnPropertyGetter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { int Goo { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] get { return 0; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, return"), // (13,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, return"), // (14,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, return"), // (16,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return"), // (17,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, return"), // (18,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, return"), // (20,10): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, return"), // (21,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, return"), // (22,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, return")); } [Fact] public void OnPropertySetter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { int Goo { get { return 0; } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (14,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, param, return"), // (15,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, param, return"), // (16,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, param, return"), // (18,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, param, return"), // (19,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, param, return"), // (20,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, param, return"), // (23,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, param, return"), // (24,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, param, return")); } [Fact] public void OnFieldEvent() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] event System.Action e; } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, field, event"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, field, event"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, field, event"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, field, event"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "method, field, event"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, field, event"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, field, event"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, field, event"), // (21,25): warning CS0067: The event 'C.e' is never used Diagnostic(ErrorCode.WRN_UnreferencedEvent, "e").WithArguments("C.e")); } [Fact, WorkItem(543977, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543977")] public void OnInterfaceFieldEvent() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } interface I { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] event System.Action e; } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, event"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, event"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, event"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, event"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, event"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "method, event"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, event"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, event"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, event")); } [Fact] public void OnCustomEvent() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] event Action E { add { } remove { } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "event"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "event"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "event"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "event"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "event"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "event"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "event"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "event"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "event"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "event")); } [Fact] public void OnEventAdder() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { event Action Goo { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] add { } remove { } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, param, return"), // (13,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, param, return"), // (14,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, param, return"), // (16,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, param, return"), // (17,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, param, return"), // (18,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, param, return"), // (21,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, param, return"), // (22,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, param, return")); } [Fact] public void OnEventRemover() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { event Action Goo { add { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] remove { } } } "; CreateCompilation(source).VerifyDiagnostics( // (14,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, param, return"), // (15,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, param, return"), // (16,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, param, return"), // (18,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, param, return"), // (19,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, param, return"), // (20,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, param, return"), // (23,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, param, return"), // (24,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, param, return")); } [Fact] public void OnTypeParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C < [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] T > { } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "typevar"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "typevar"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "typevar"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "typevar"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "typevar"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "typevar"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "typevar"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "typevar"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "typevar"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "typevar")); } [Fact] public void OnMethodParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { void f( [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int x ) { } } "; CreateCompilation(source).VerifyDiagnostics( // (11,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "param"), // (12,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "param"), // (13,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "param"), // (14,10): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "param"), // (15,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param"), // (16,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param"), // (17,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "param"), // (18,10): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "param"), // (20,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "param"), // (21,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "param")); } [Fact] public void OnDelegateParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } delegate void D( [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int x ); "; CreateCompilation(source).VerifyDiagnostics( // (9,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "param"), // (10,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "param"), // (11,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "param"), // (12,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "param"), // (13,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param"), // (14,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param"), // (15,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "param"), // (16,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "param"), // (18,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "param"), // (19,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "param")); } [Fact] public void OnIndexerParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { int this[ [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int x] { get { return 0; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (11,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "param"), // (12,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "param"), // (13,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "param"), // (14,10): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "param"), // (15,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param"), // (16,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param"), // (17,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "param"), // (18,10): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "param"), // (20,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "param"), // (21,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "param")); } [Fact] public void UnrecognizedLocations() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [class: A] [struct: A] [interface: A] [delegate: A] [enum: A] [add: A] [remove: A] [get: A] [set: A] class C { }"; CreateCompilation(source).VerifyDiagnostics( // (7,2): warning CS0658: 'class' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "class").WithArguments("class", "type"), // (8,2): warning CS0658: 'struct' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "struct").WithArguments("struct", "type"), // (9,2): warning CS0658: 'interface' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "interface").WithArguments("interface", "type"), // (10,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type"), // (11,2): warning CS0658: 'enum' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "enum").WithArguments("enum", "type"), // (12,2): warning CS0658: 'add' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "add").WithArguments("add", "type"), // (13,2): warning CS0658: 'remove' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "remove").WithArguments("remove", "type"), // (14,2): warning CS0658: 'get' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "get").WithArguments("get", "type"), // (15,2): warning CS0658: 'set' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "set").WithArguments("set", "type")); } [Fact, WorkItem(545555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545555")] public void AttributesWithInvalidLocationNotEmitted() { var source = @" using System; public class goo { public static void Main() { object[] o = typeof(goo).GetMethod(""Boo"").GetCustomAttributes(typeof(A), false); Console.WriteLine(""Attribute Count={0}"", o.Length); } [goo: A] [method: A] public int Boo(int i) { return 1; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CompileAndVerify(source, expectedOutput: "Attribute Count=1").VerifyDiagnostics( // (12,6): warning CS0658: 'goo' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "goo").WithArguments("goo", "method, return")); } [WorkItem(537613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537613"), WorkItem(537738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537738")] [Fact] public void CS0246ERR_SingleTypeNameNotFound_VerbatimIdentifierAttributeTarget() { CreateCompilation(@"class A { [@return:X] void B() { } }").VerifyDiagnostics( // (1,20): error CS0246: The type or namespace name 'XAttribute' could not be found (are you missing a using directive or an assembly reference?) // class A { [@return:X] void B() { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("XAttribute").WithLocation(1, 20), // (1,20): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // class A { [@return:X] void B() { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(1, 20)); } [WorkItem(537613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537613"), WorkItem(537738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537738")] [Fact] public void CS0246ERR_SingleTypeNameNotFound_VerbatimIdentifierAttributeTargetAndAttribute() { var source = @" using System; class X: Attribute {} class XAttribute: Attribute {} class A { [return:X] void M() { } } // Ambiguous class B { [@return:X] void M() { } } // Ambiguous class C { [return:@X] void M() { } } // Fine, binds to X class D { [@return:@X] void M() { } } // Fine, binds to X "; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute' // class A { [return:X] void M() { } } // Ambiguous Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "X").WithArguments("X", "X", "XAttribute"), // (8,20): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute' // class B { [@return:X] void M() { } } // Ambiguous Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "X").WithArguments("X", "X", "XAttribute")); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/Core/Portable/ExtractMethod/SelectionValidator.NullSelectionResult.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; namespace Microsoft.CodeAnalysis.ExtractMethod { internal partial class SelectionValidator { // null object protected class NullSelectionResult : SelectionResult { public NullSelectionResult() : this(OperationStatus.FailedWithUnknownReason) { } protected NullSelectionResult(OperationStatus status) : base(status) { } protected override bool UnderAnonymousOrLocalMethod(SyntaxToken token, SyntaxToken firstToken, SyntaxToken lastToken) => throw new InvalidOperationException(); public override bool ContainingScopeHasAsyncKeyword() => throw new InvalidOperationException(); public override SyntaxNode GetContainingScope() => throw new InvalidOperationException(); public override ITypeSymbol GetContainingScopeType() => throw new InvalidOperationException(); } protected class ErrorSelectionResult : NullSelectionResult { public ErrorSelectionResult(OperationStatus status) : base(status.MakeFail()) { } } } }
// 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; namespace Microsoft.CodeAnalysis.ExtractMethod { internal partial class SelectionValidator { // null object protected class NullSelectionResult : SelectionResult { public NullSelectionResult() : this(OperationStatus.FailedWithUnknownReason) { } protected NullSelectionResult(OperationStatus status) : base(status) { } protected override bool UnderAnonymousOrLocalMethod(SyntaxToken token, SyntaxToken firstToken, SyntaxToken lastToken) => throw new InvalidOperationException(); public override bool ContainingScopeHasAsyncKeyword() => throw new InvalidOperationException(); public override SyntaxNode GetContainingScope() => throw new InvalidOperationException(); public override ITypeSymbol GetContainingScopeType() => throw new InvalidOperationException(); } protected class ErrorSelectionResult : NullSelectionResult { public ErrorSelectionResult(OperationStatus status) : base(status.MakeFail()) { } } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/VisualStudio/Core/Def/Implementation/CommonControls/MemberSelection.xaml
<UserControl x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls.MemberSelection" x:ClassModifier="internal" x:Name="MemberSelectionControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:utilities="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Utilities" xmlns:commoncontrols="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <UserControl.Resources> <Thickness x:Key="ButtonControlsPadding">2, 4, 4, 2</Thickness> <utilities:BooleanReverseConverter x:Key="BooleanReverseConverter"/> </UserControl.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <DataGrid x:Uid="MemberSelectionGrid" x:Name="MemberSelectionGrid" Grid.Column="0" Margin="2, 5, 12, 2" SelectionMode="Extended" AutoGenerateColumns="False" HeadersVisibility="Column" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" CanUserResizeColumns="False" CanUserResizeRows="False" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False" CanUserSortColumns="False" GridLinesVisibility="None" ScrollViewer.VerticalScrollBarVisibility="Auto" CanUserReorderColumns="False" Focusable="True" MinWidth="334" Height="Auto" Background="White" AutomationProperties.Name="{Binding SelectMemberListViewAutomationText}" ItemsSource="{Binding Members, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True, Mode=TwoWay}"> <DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="BorderThickness" Value="0"/> <Setter Property="Focusable" Value="False"/> <Setter Property="AutomationProperties.Name" Value="{Binding SymbolName}" /> </Style> </DataGrid.CellStyle> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Setter Property="AutomationProperties.Name" Value="{Binding RowSelectionAutomationText}"/> </Style> </DataGrid.RowStyle> <DataGrid.Columns> <DataGridTemplateColumn Width="Auto"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox AutomationProperties.Name="{Binding SymbolAutomationText}" AutomationProperties.AutomationId="{Binding SymbolName}" IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" Width="Auto" IsEnabled="{Binding IsCheckable, UpdateSourceTrigger=PropertyChanged}" Focusable="True" ToolTipService.ShowOnDisabled="True" ToolTipService.IsEnabled="{Binding IsCheckable, Converter={StaticResource BooleanReverseConverter}, UpdateSourceTrigger=PropertyChanged}" ToolTipService.ToolTip="{Binding HelpText}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Width="*"> <DataGridTemplateColumn.Header> <TextBlock Text="{Binding ElementName=MemberSelectionControl, Path=MembersHeader}"/> </DataGridTemplateColumn.Header> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" MinWidth="186" Width="Auto" Margin="5, 2, 0, 2"> <Image x:Name="GlyphOfMember" Margin="8, 0, 5, 0" Source="{Binding Glyph}"/> <TextBlock x:Name="MemberName" Text="{Binding SymbolName}" Margin="0, 0, 5, 0" ToolTip="{Binding Accessibility}"/> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Width="100"> <DataGridTemplateColumn.Header> <TextBlock Text="{Binding ElementName=MemberSelectionControl, Path=MakeAbstractHeader}"/> </DataGridTemplateColumn.Header> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" Visibility="{Binding MakeAbstractVisibility}" IsEnabled="{Binding IsMakeAbstractCheckable, UpdateSourceTrigger=PropertyChanged}" AutomationProperties.Name="{Binding MakeAbstractCheckBoxAutomationText}" Focusable="True" Margin="0, 2, 0, 2" IsChecked="{Binding MakeAbstract, UpdateSourceTrigger=PropertyChanged}"> </CheckBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> <StackPanel Grid.Column="1" Orientation="Vertical" VerticalAlignment="Top" HorizontalAlignment="Center" Margin="0, 4, 0, 0" Width="Auto"> <Button x:Name="SelectAllButton" x:Uid="SelectAllButton" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Content="{Binding ElementName=MemberSelectionControl, Path=SelectAll}" Click="SelectAllButton_Click" Margin="2, 2, 2, 7" Width="Auto" Height="Auto" /> <Button x:Name="DeselectAllButton" x:Uid="DeselectAllButton" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Content="{Binding ElementName=MemberSelectionControl, Path=DeselectAll}" Click="DeselectAllButton_Click" Margin="2, 2, 2, 7" Width="Auto" Height="Auto" /> <Button x:Name="SelecDependentsButton" x:Uid="SelecDependentsButton" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Content="{Binding ElementName=MemberSelectionControl, Path=SelectDependents}" Click="SelectDependentsButton_Click" Margin="2, 2, 2, 7" Width="Auto" Height="Auto"/> <Button x:Name="SelectPublicButton" x:Uid="SelectPublicButton" Content="{Binding ElementName=MemberSelectionControl, Path=SelectPublic}" Margin="2, 0, 2, 0" Click="SelectPublic_Click" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Width="Auto" Height="Auto"/> </StackPanel> </Grid> </UserControl>
<UserControl x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls.MemberSelection" x:ClassModifier="internal" x:Name="MemberSelectionControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:utilities="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Utilities" xmlns:commoncontrols="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <UserControl.Resources> <Thickness x:Key="ButtonControlsPadding">2, 4, 4, 2</Thickness> <utilities:BooleanReverseConverter x:Key="BooleanReverseConverter"/> </UserControl.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <DataGrid x:Uid="MemberSelectionGrid" x:Name="MemberSelectionGrid" Grid.Column="0" Margin="2, 5, 12, 2" SelectionMode="Extended" AutoGenerateColumns="False" HeadersVisibility="Column" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" CanUserResizeColumns="False" CanUserResizeRows="False" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False" CanUserSortColumns="False" GridLinesVisibility="None" ScrollViewer.VerticalScrollBarVisibility="Auto" CanUserReorderColumns="False" Focusable="True" MinWidth="334" Height="Auto" Background="White" AutomationProperties.Name="{Binding SelectMemberListViewAutomationText}" ItemsSource="{Binding Members, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True, Mode=TwoWay}"> <DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="BorderThickness" Value="0"/> <Setter Property="Focusable" Value="False"/> <Setter Property="AutomationProperties.Name" Value="{Binding SymbolName}" /> </Style> </DataGrid.CellStyle> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Setter Property="AutomationProperties.Name" Value="{Binding RowSelectionAutomationText}"/> </Style> </DataGrid.RowStyle> <DataGrid.Columns> <DataGridTemplateColumn Width="Auto"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox AutomationProperties.Name="{Binding SymbolAutomationText}" AutomationProperties.AutomationId="{Binding SymbolName}" IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" Width="Auto" IsEnabled="{Binding IsCheckable, UpdateSourceTrigger=PropertyChanged}" Focusable="True" ToolTipService.ShowOnDisabled="True" ToolTipService.IsEnabled="{Binding IsCheckable, Converter={StaticResource BooleanReverseConverter}, UpdateSourceTrigger=PropertyChanged}" ToolTipService.ToolTip="{Binding HelpText}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Width="*"> <DataGridTemplateColumn.Header> <TextBlock Text="{Binding ElementName=MemberSelectionControl, Path=MembersHeader}"/> </DataGridTemplateColumn.Header> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" MinWidth="186" Width="Auto" Margin="5, 2, 0, 2"> <Image x:Name="GlyphOfMember" Margin="8, 0, 5, 0" Source="{Binding Glyph}"/> <TextBlock x:Name="MemberName" Text="{Binding SymbolName}" Margin="0, 0, 5, 0" ToolTip="{Binding Accessibility}"/> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Width="100"> <DataGridTemplateColumn.Header> <TextBlock Text="{Binding ElementName=MemberSelectionControl, Path=MakeAbstractHeader}"/> </DataGridTemplateColumn.Header> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" Visibility="{Binding MakeAbstractVisibility}" IsEnabled="{Binding IsMakeAbstractCheckable, UpdateSourceTrigger=PropertyChanged}" AutomationProperties.Name="{Binding MakeAbstractCheckBoxAutomationText}" Focusable="True" Margin="0, 2, 0, 2" IsChecked="{Binding MakeAbstract, UpdateSourceTrigger=PropertyChanged}"> </CheckBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> <StackPanel Grid.Column="1" Orientation="Vertical" VerticalAlignment="Top" HorizontalAlignment="Center" Margin="0, 4, 0, 0" Width="Auto"> <Button x:Name="SelectAllButton" x:Uid="SelectAllButton" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Content="{Binding ElementName=MemberSelectionControl, Path=SelectAll}" Click="SelectAllButton_Click" Margin="2, 2, 2, 7" Width="Auto" Height="Auto" /> <Button x:Name="DeselectAllButton" x:Uid="DeselectAllButton" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Content="{Binding ElementName=MemberSelectionControl, Path=DeselectAll}" Click="DeselectAllButton_Click" Margin="2, 2, 2, 7" Width="Auto" Height="Auto" /> <Button x:Name="SelecDependentsButton" x:Uid="SelecDependentsButton" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Content="{Binding ElementName=MemberSelectionControl, Path=SelectDependents}" Click="SelectDependentsButton_Click" Margin="2, 2, 2, 7" Width="Auto" Height="Auto"/> <Button x:Name="SelectPublicButton" x:Uid="SelectPublicButton" Content="{Binding ElementName=MemberSelectionControl, Path=SelectPublic}" Margin="2, 0, 2, 0" Click="SelectPublic_Click" Padding="{StaticResource ResourceKey=ButtonControlsPadding}" Width="Auto" Height="Auto"/> </StackPanel> </Grid> </UserControl>
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/EditorFeatures/VisualBasic/EndConstructGeneration/EndConstructStatementVisitor_LambdaHeader.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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration Partial Friend Class EndConstructStatementVisitor Public Overrides Function VisitLambdaHeader(node As LambdaHeaderSyntax) As AbstractEndConstructResult Dim singleLineExpressionSyntax = TryCast(node.Parent, SingleLineLambdaExpressionSyntax) If singleLineExpressionSyntax IsNot Nothing Then Return TransformSingleLineLambda(singleLineExpressionSyntax) Else Return SpitNormalLambdaEnding(node) End If End Function Private Function TransformSingleLineLambda(originalNode As SingleLineLambdaExpressionSyntax) As AbstractEndConstructResult ' If there is newline trivia on the end of the node, we need to pull that off to stick it back on at the very end of this transformation Dim newLineTrivia = originalNode.GetTrailingTrivia().SkipWhile(Function(t) Not t.IsKind(SyntaxKind.EndOfLineTrivia)) Dim node = originalNode.WithTrailingTrivia(originalNode.GetTrailingTrivia().TakeWhile(Function(t) Not t.IsKind(SyntaxKind.EndOfLineTrivia))) Dim tokenNextToLambda = originalNode.GetLastToken().GetNextToken() Dim isNextToXmlEmbeddedExpression = tokenNextToLambda.IsKind(SyntaxKind.PercentGreaterThanToken) AndAlso tokenNextToLambda.Parent.IsKind(SyntaxKind.XmlEmbeddedExpression) Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(originalNode.SpanStart) Dim indentedWhitespace = aligningWhitespace & " " ' Generate the end statement since we can easily share that code Dim endStatementKind = If(originalNode.Kind = SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.EndSubStatement, SyntaxKind.EndFunctionStatement) Dim endStatement = SyntaxFactory.EndBlockStatement(endStatementKind, SyntaxFactory.Token(originalNode.SubOrFunctionHeader.DeclarationKeyword.Kind).WithLeadingTrivia(SyntaxFactory.WhitespaceTrivia(" "))) _ .WithLeadingTrivia(SyntaxFactory.WhitespaceTrivia(aligningWhitespace)) _ .WithTrailingTrivia(If(isNextToXmlEmbeddedExpression, SyntaxFactory.TriviaList(SyntaxFactory.WhitespaceTrivia(" ")), newLineTrivia)) ' We are hitting enter after a single line. Let's transform it to a multi-line form If node.Kind = SyntaxKind.SingleLineSubLambdaExpression Then ' If we have Sub() End Sub as a lambda, we're better off just doing nothing smart If node.Body.IsKind(SyntaxKind.EndSubStatement) Then Return Nothing End If ' Update the new header Dim newHeader = node.SubOrFunctionHeader If newHeader.ParameterList Is Nothing OrElse (newHeader.ParameterList.OpenParenToken.IsMissing AndAlso newHeader.ParameterList.CloseParenToken.IsMissing) Then newHeader = newHeader.WithParameterList(SyntaxFactory.ParameterList()) End If newHeader = newHeader.WithTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)) ' Update the body with a newline Dim newBody = DirectCast(node.Body, StatementSyntax).WithAppendedTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)) Dim newBodyHasCode = False ' If it actually contains something, intent it too. Otherwise, we'll just let the smart indenter position If Not String.IsNullOrWhiteSpace(newBody.ToFullString()) Then newBody = newBody.WithPrependedLeadingTrivia(SyntaxFactory.WhitespaceTrivia(indentedWhitespace)) newBodyHasCode = True End If Dim newExpression = SyntaxFactory.MultiLineSubLambdaExpression( subOrFunctionHeader:=newHeader, statements:=SyntaxFactory.SingletonList(newBody), endSubOrFunctionStatement:=endStatement) Return New ReplaceSpanResult(originalNode.FullSpan.ToSnapshotSpan(_subjectBuffer.CurrentSnapshot), newExpression.ToFullString(), If(newBodyHasCode, CType(newExpression.Statements.First().SpanStart, Integer?), Nothing)) Else If node.Body.IsMissing Then If node.Body.GetTrailingTrivia().Any(Function(t) t.IsKind(SyntaxKind.SkippedTokensTrivia)) Then ' If we had to skip tokens, we're probably just going to break more than we fix Return Nothing End If ' It's still missing entirely, so just spit normally Return CreateSpitLinesForLambdaHeader(node.SubOrFunctionHeader, isNextToXmlEmbeddedExpression, originalNode.SpanStart) End If Dim newHeader = node.SubOrFunctionHeader.WithTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)) Dim newBody = SyntaxFactory.ReturnStatement(SyntaxFactory.Token(SyntaxKind.ReturnKeyword).WithTrailingTrivia(SyntaxFactory.WhitespaceTrivia(" ")), DirectCast(node.Body, ExpressionSyntax)) _ .WithPrependedLeadingTrivia(SyntaxFactory.WhitespaceTrivia(indentedWhitespace)) _ .WithAppendedTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)) Dim newExpression = SyntaxFactory.MultiLineSubLambdaExpression( subOrFunctionHeader:=newHeader, statements:=SyntaxFactory.SingletonList(Of StatementSyntax)(newBody), endSubOrFunctionStatement:=endStatement) ' Fish our body back out so we can figure out relative spans newBody = DirectCast(newExpression.Statements.First(), ReturnStatementSyntax) Return New ReplaceSpanResult(originalNode.FullSpan.ToSnapshotSpan(_subjectBuffer.CurrentSnapshot), newExpression.ToFullString(), newBody.ReturnKeyword.FullSpan.End) End If Return Nothing End Function Private Function SpitNormalLambdaEnding(node As LambdaHeaderSyntax) As AbstractEndConstructResult Dim needsEnd = node.GetAncestorsOrThis(Of MultiLineLambdaExpressionSyntax)().Any(Function(block) block.EndSubOrFunctionStatement.IsMissing AndAlso block.IsMultiLineLambda()) ' We have to be careful here: just because the Lambda's End isn't missing doesn't mean we shouldn't spit a ' End Sub / End Function. A good example is an unterminated multi-line sub in a sub, like this: ' ' Sub goo() ' Dim x = Sub() ' End Sub ' ' Obviously the parser has an ambiguity here, and so it chooses to parse the End Sub as being the terminator ' for the lambda. In this case, we'll notice that this lambda has a parent method body that uses the same ' Sub/Function keyword and is missing it's end construct, indicating that we should still spit. Dim containingMethodBlock = node.GetAncestor(Of MethodBlockBaseSyntax)() If containingMethodBlock IsNot Nothing AndAlso containingMethodBlock.EndBlockStatement.IsMissing Then ' Is this containing method the same type (Sub/Function) as the lambda? If containingMethodBlock.BlockStatement.DeclarationKeyword.Kind = node.DeclarationKeyword.Kind Then needsEnd = True End If End If If needsEnd Then Return CreateSpitLinesForLambdaHeader(node) Else Return Nothing End If End Function Private Function CreateSpitLinesForLambdaHeader(node As LambdaHeaderSyntax, Optional isNextToXmlEmbeddedExpression As Boolean = False, Optional originalNodeSpanStart? As Integer = Nothing) As AbstractEndConstructResult Dim spanStart As Integer = If(originalNodeSpanStart.HasValue, originalNodeSpanStart.Value, node.SpanStart) Dim endConstruct = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(spanStart) & "End " & node.DeclarationKeyword.ToString() ' We may wish to spit () at the end of if we are missing our parenthesis If node.ParameterList Is Nothing OrElse (node.ParameterList.OpenParenToken.IsMissing AndAlso node.ParameterList.CloseParenToken.IsMissing) Then Return New SpitLinesResult({"()", "", endConstruct}, startOnCurrentLine:=True) Else Return New SpitLinesResult({"", If(isNextToXmlEmbeddedExpression, endConstruct & " ", endConstruct)}) End If 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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration Partial Friend Class EndConstructStatementVisitor Public Overrides Function VisitLambdaHeader(node As LambdaHeaderSyntax) As AbstractEndConstructResult Dim singleLineExpressionSyntax = TryCast(node.Parent, SingleLineLambdaExpressionSyntax) If singleLineExpressionSyntax IsNot Nothing Then Return TransformSingleLineLambda(singleLineExpressionSyntax) Else Return SpitNormalLambdaEnding(node) End If End Function Private Function TransformSingleLineLambda(originalNode As SingleLineLambdaExpressionSyntax) As AbstractEndConstructResult ' If there is newline trivia on the end of the node, we need to pull that off to stick it back on at the very end of this transformation Dim newLineTrivia = originalNode.GetTrailingTrivia().SkipWhile(Function(t) Not t.IsKind(SyntaxKind.EndOfLineTrivia)) Dim node = originalNode.WithTrailingTrivia(originalNode.GetTrailingTrivia().TakeWhile(Function(t) Not t.IsKind(SyntaxKind.EndOfLineTrivia))) Dim tokenNextToLambda = originalNode.GetLastToken().GetNextToken() Dim isNextToXmlEmbeddedExpression = tokenNextToLambda.IsKind(SyntaxKind.PercentGreaterThanToken) AndAlso tokenNextToLambda.Parent.IsKind(SyntaxKind.XmlEmbeddedExpression) Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(originalNode.SpanStart) Dim indentedWhitespace = aligningWhitespace & " " ' Generate the end statement since we can easily share that code Dim endStatementKind = If(originalNode.Kind = SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.EndSubStatement, SyntaxKind.EndFunctionStatement) Dim endStatement = SyntaxFactory.EndBlockStatement(endStatementKind, SyntaxFactory.Token(originalNode.SubOrFunctionHeader.DeclarationKeyword.Kind).WithLeadingTrivia(SyntaxFactory.WhitespaceTrivia(" "))) _ .WithLeadingTrivia(SyntaxFactory.WhitespaceTrivia(aligningWhitespace)) _ .WithTrailingTrivia(If(isNextToXmlEmbeddedExpression, SyntaxFactory.TriviaList(SyntaxFactory.WhitespaceTrivia(" ")), newLineTrivia)) ' We are hitting enter after a single line. Let's transform it to a multi-line form If node.Kind = SyntaxKind.SingleLineSubLambdaExpression Then ' If we have Sub() End Sub as a lambda, we're better off just doing nothing smart If node.Body.IsKind(SyntaxKind.EndSubStatement) Then Return Nothing End If ' Update the new header Dim newHeader = node.SubOrFunctionHeader If newHeader.ParameterList Is Nothing OrElse (newHeader.ParameterList.OpenParenToken.IsMissing AndAlso newHeader.ParameterList.CloseParenToken.IsMissing) Then newHeader = newHeader.WithParameterList(SyntaxFactory.ParameterList()) End If newHeader = newHeader.WithTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)) ' Update the body with a newline Dim newBody = DirectCast(node.Body, StatementSyntax).WithAppendedTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)) Dim newBodyHasCode = False ' If it actually contains something, intent it too. Otherwise, we'll just let the smart indenter position If Not String.IsNullOrWhiteSpace(newBody.ToFullString()) Then newBody = newBody.WithPrependedLeadingTrivia(SyntaxFactory.WhitespaceTrivia(indentedWhitespace)) newBodyHasCode = True End If Dim newExpression = SyntaxFactory.MultiLineSubLambdaExpression( subOrFunctionHeader:=newHeader, statements:=SyntaxFactory.SingletonList(newBody), endSubOrFunctionStatement:=endStatement) Return New ReplaceSpanResult(originalNode.FullSpan.ToSnapshotSpan(_subjectBuffer.CurrentSnapshot), newExpression.ToFullString(), If(newBodyHasCode, CType(newExpression.Statements.First().SpanStart, Integer?), Nothing)) Else If node.Body.IsMissing Then If node.Body.GetTrailingTrivia().Any(Function(t) t.IsKind(SyntaxKind.SkippedTokensTrivia)) Then ' If we had to skip tokens, we're probably just going to break more than we fix Return Nothing End If ' It's still missing entirely, so just spit normally Return CreateSpitLinesForLambdaHeader(node.SubOrFunctionHeader, isNextToXmlEmbeddedExpression, originalNode.SpanStart) End If Dim newHeader = node.SubOrFunctionHeader.WithTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)) Dim newBody = SyntaxFactory.ReturnStatement(SyntaxFactory.Token(SyntaxKind.ReturnKeyword).WithTrailingTrivia(SyntaxFactory.WhitespaceTrivia(" ")), DirectCast(node.Body, ExpressionSyntax)) _ .WithPrependedLeadingTrivia(SyntaxFactory.WhitespaceTrivia(indentedWhitespace)) _ .WithAppendedTrailingTrivia(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)) Dim newExpression = SyntaxFactory.MultiLineSubLambdaExpression( subOrFunctionHeader:=newHeader, statements:=SyntaxFactory.SingletonList(Of StatementSyntax)(newBody), endSubOrFunctionStatement:=endStatement) ' Fish our body back out so we can figure out relative spans newBody = DirectCast(newExpression.Statements.First(), ReturnStatementSyntax) Return New ReplaceSpanResult(originalNode.FullSpan.ToSnapshotSpan(_subjectBuffer.CurrentSnapshot), newExpression.ToFullString(), newBody.ReturnKeyword.FullSpan.End) End If Return Nothing End Function Private Function SpitNormalLambdaEnding(node As LambdaHeaderSyntax) As AbstractEndConstructResult Dim needsEnd = node.GetAncestorsOrThis(Of MultiLineLambdaExpressionSyntax)().Any(Function(block) block.EndSubOrFunctionStatement.IsMissing AndAlso block.IsMultiLineLambda()) ' We have to be careful here: just because the Lambda's End isn't missing doesn't mean we shouldn't spit a ' End Sub / End Function. A good example is an unterminated multi-line sub in a sub, like this: ' ' Sub goo() ' Dim x = Sub() ' End Sub ' ' Obviously the parser has an ambiguity here, and so it chooses to parse the End Sub as being the terminator ' for the lambda. In this case, we'll notice that this lambda has a parent method body that uses the same ' Sub/Function keyword and is missing it's end construct, indicating that we should still spit. Dim containingMethodBlock = node.GetAncestor(Of MethodBlockBaseSyntax)() If containingMethodBlock IsNot Nothing AndAlso containingMethodBlock.EndBlockStatement.IsMissing Then ' Is this containing method the same type (Sub/Function) as the lambda? If containingMethodBlock.BlockStatement.DeclarationKeyword.Kind = node.DeclarationKeyword.Kind Then needsEnd = True End If End If If needsEnd Then Return CreateSpitLinesForLambdaHeader(node) Else Return Nothing End If End Function Private Function CreateSpitLinesForLambdaHeader(node As LambdaHeaderSyntax, Optional isNextToXmlEmbeddedExpression As Boolean = False, Optional originalNodeSpanStart? As Integer = Nothing) As AbstractEndConstructResult Dim spanStart As Integer = If(originalNodeSpanStart.HasValue, originalNodeSpanStart.Value, node.SpanStart) Dim endConstruct = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(spanStart) & "End " & node.DeclarationKeyword.ToString() ' We may wish to spit () at the end of if we are missing our parenthesis If node.ParameterList Is Nothing OrElse (node.ParameterList.OpenParenToken.IsMissing AndAlso node.ParameterList.CloseParenToken.IsMissing) Then Return New SpitLinesResult({"()", "", endConstruct}, startOnCurrentLine:=True) Else Return New SpitLinesResult({"", If(isNextToXmlEmbeddedExpression, endConstruct & " ", endConstruct)}) End If End Function End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/Core/Portable/Completion/CompletionList.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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// The set of completions to present to the user. /// </summary> public sealed class CompletionList { private readonly bool _isExclusive; /// <summary> /// The completion items to present to the user. /// </summary> public ImmutableArray<CompletionItem> Items { get; } /// <summary> /// The span of the syntax element at the caret position when the <see cref="CompletionList"/> was created. /// Individual <see cref="CompletionItem"/> spans may vary. /// </summary> [Obsolete("Not used anymore. CompletionList.Span is used instead.", error: true)] public TextSpan DefaultSpan { get; } /// <summary> /// The span of the syntax element at the caret position when the <see cref="CompletionList"/> /// was created. /// /// The span identifies the text in the document that is used to filter the initial list /// presented to the user, and typically represents the region of the document that will /// be changed if this item is committed. /// </summary> public TextSpan Span { get; } /// <summary> /// The rules used to control behavior of the completion list shown to the user during typing. /// </summary> public CompletionRules Rules { get; } /// <summary> /// An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode. /// Suggestion mode disables autoselection of items in the list, giving preference to the text typed by the user unless a specific item is selected manually. /// Specifying a <see cref="SuggestionModeItem"/> is a request that the completion host operate in suggestion mode. /// The item specified determines the text displayed and the description associated with it unless a different item is manually selected. /// No text is ever inserted when this item is completed, leaving the text the user typed instead. /// </summary> public CompletionItem SuggestionModeItem { get; } private CompletionList( TextSpan defaultSpan, ImmutableArray<CompletionItem> items, CompletionRules rules, CompletionItem suggestionModeItem, bool isExclusive) { Span = defaultSpan; Items = items.NullToEmpty(); Rules = rules ?? CompletionRules.Default; SuggestionModeItem = suggestionModeItem; _isExclusive = isExclusive; foreach (var item in Items) { item.Span = defaultSpan; } } /// <summary> /// Creates a new <see cref="CompletionList"/> instance. /// </summary> /// <param name="defaultSpan">The span of the syntax element at the caret position when the <see cref="CompletionList"/> was created.</param> /// <param name="items">The completion items to present to the user.</param> /// <param name="rules">The rules used to control behavior of the completion list shown to the user during typing.</param> /// <param name="suggestionModeItem">An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode.</param> /// <returns></returns> public static CompletionList Create( TextSpan defaultSpan, ImmutableArray<CompletionItem> items, CompletionRules rules = null, CompletionItem suggestionModeItem = null) { return Create(defaultSpan, items, rules, suggestionModeItem, isExclusive: false); } internal static CompletionList Create( TextSpan defaultSpan, ImmutableArray<CompletionItem> items, CompletionRules rules, CompletionItem suggestionModeItem, bool isExclusive) { return new CompletionList(defaultSpan, items, rules, suggestionModeItem, isExclusive); } private CompletionList With( Optional<TextSpan> span = default, Optional<ImmutableArray<CompletionItem>> items = default, Optional<CompletionRules> rules = default, Optional<CompletionItem> suggestionModeItem = default) { var newSpan = span.HasValue ? span.Value : Span; var newItems = items.HasValue ? items.Value : Items; var newRules = rules.HasValue ? rules.Value : Rules; var newSuggestionModeItem = suggestionModeItem.HasValue ? suggestionModeItem.Value : SuggestionModeItem; if (newSpan == Span && newItems == Items && newRules == Rules && newSuggestionModeItem == SuggestionModeItem) { return this; } else { return Create(newSpan, newItems, newRules, newSuggestionModeItem); } } /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="DefaultSpan"/> property changed. /// </summary> [Obsolete("Not used anymore. Use WithSpan instead.", error: true)] public CompletionList WithDefaultSpan(TextSpan span) => With(span: span); public CompletionList WithSpan(TextSpan span) => With(span: span); /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="Items"/> property changed. /// </summary> public CompletionList WithItems(ImmutableArray<CompletionItem> items) => With(items: items); /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="Rules"/> property changed. /// </summary> public CompletionList WithRules(CompletionRules rules) => With(rules: rules); /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="SuggestionModeItem"/> property changed. /// </summary> public CompletionList WithSuggestionModeItem(CompletionItem suggestionModeItem) => With(suggestionModeItem: suggestionModeItem); /// <summary> /// The default <see cref="CompletionList"/> returned when no items are found to populate the list. /// </summary> public static readonly CompletionList Empty = new( default, default, CompletionRules.Default, suggestionModeItem: null, isExclusive: false); internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly CompletionList _completionList; public TestAccessor(CompletionList completionList) => _completionList = completionList; internal bool IsExclusive => _completionList._isExclusive; } } }
// 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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// The set of completions to present to the user. /// </summary> public sealed class CompletionList { private readonly bool _isExclusive; /// <summary> /// The completion items to present to the user. /// </summary> public ImmutableArray<CompletionItem> Items { get; } /// <summary> /// The span of the syntax element at the caret position when the <see cref="CompletionList"/> was created. /// Individual <see cref="CompletionItem"/> spans may vary. /// </summary> [Obsolete("Not used anymore. CompletionList.Span is used instead.", error: true)] public TextSpan DefaultSpan { get; } /// <summary> /// The span of the syntax element at the caret position when the <see cref="CompletionList"/> /// was created. /// /// The span identifies the text in the document that is used to filter the initial list /// presented to the user, and typically represents the region of the document that will /// be changed if this item is committed. /// </summary> public TextSpan Span { get; } /// <summary> /// The rules used to control behavior of the completion list shown to the user during typing. /// </summary> public CompletionRules Rules { get; } /// <summary> /// An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode. /// Suggestion mode disables autoselection of items in the list, giving preference to the text typed by the user unless a specific item is selected manually. /// Specifying a <see cref="SuggestionModeItem"/> is a request that the completion host operate in suggestion mode. /// The item specified determines the text displayed and the description associated with it unless a different item is manually selected. /// No text is ever inserted when this item is completed, leaving the text the user typed instead. /// </summary> public CompletionItem SuggestionModeItem { get; } private CompletionList( TextSpan defaultSpan, ImmutableArray<CompletionItem> items, CompletionRules rules, CompletionItem suggestionModeItem, bool isExclusive) { Span = defaultSpan; Items = items.NullToEmpty(); Rules = rules ?? CompletionRules.Default; SuggestionModeItem = suggestionModeItem; _isExclusive = isExclusive; foreach (var item in Items) { item.Span = defaultSpan; } } /// <summary> /// Creates a new <see cref="CompletionList"/> instance. /// </summary> /// <param name="defaultSpan">The span of the syntax element at the caret position when the <see cref="CompletionList"/> was created.</param> /// <param name="items">The completion items to present to the user.</param> /// <param name="rules">The rules used to control behavior of the completion list shown to the user during typing.</param> /// <param name="suggestionModeItem">An optional <see cref="CompletionItem"/> that appears selected in the list presented to the user during suggestion mode.</param> /// <returns></returns> public static CompletionList Create( TextSpan defaultSpan, ImmutableArray<CompletionItem> items, CompletionRules rules = null, CompletionItem suggestionModeItem = null) { return Create(defaultSpan, items, rules, suggestionModeItem, isExclusive: false); } internal static CompletionList Create( TextSpan defaultSpan, ImmutableArray<CompletionItem> items, CompletionRules rules, CompletionItem suggestionModeItem, bool isExclusive) { return new CompletionList(defaultSpan, items, rules, suggestionModeItem, isExclusive); } private CompletionList With( Optional<TextSpan> span = default, Optional<ImmutableArray<CompletionItem>> items = default, Optional<CompletionRules> rules = default, Optional<CompletionItem> suggestionModeItem = default) { var newSpan = span.HasValue ? span.Value : Span; var newItems = items.HasValue ? items.Value : Items; var newRules = rules.HasValue ? rules.Value : Rules; var newSuggestionModeItem = suggestionModeItem.HasValue ? suggestionModeItem.Value : SuggestionModeItem; if (newSpan == Span && newItems == Items && newRules == Rules && newSuggestionModeItem == SuggestionModeItem) { return this; } else { return Create(newSpan, newItems, newRules, newSuggestionModeItem); } } /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="DefaultSpan"/> property changed. /// </summary> [Obsolete("Not used anymore. Use WithSpan instead.", error: true)] public CompletionList WithDefaultSpan(TextSpan span) => With(span: span); public CompletionList WithSpan(TextSpan span) => With(span: span); /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="Items"/> property changed. /// </summary> public CompletionList WithItems(ImmutableArray<CompletionItem> items) => With(items: items); /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="Rules"/> property changed. /// </summary> public CompletionList WithRules(CompletionRules rules) => With(rules: rules); /// <summary> /// Creates a copy of this <see cref="CompletionList"/> with the <see cref="SuggestionModeItem"/> property changed. /// </summary> public CompletionList WithSuggestionModeItem(CompletionItem suggestionModeItem) => With(suggestionModeItem: suggestionModeItem); /// <summary> /// The default <see cref="CompletionList"/> returned when no items are found to populate the list. /// </summary> public static readonly CompletionList Empty = new( default, default, CompletionRules.Default, suggestionModeItem: null, isExclusive: false); internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly CompletionList _completionList; public TestAccessor(CompletionList completionList) => _completionList = completionList; internal bool IsExclusive => _completionList._isExclusive; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.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.Collections.Immutable Imports System.ComponentModel Imports System.Globalization Imports System.IO Imports System.IO.MemoryMappedFiles Imports System.Reflection Imports System.Reflection.Metadata Imports System.Reflection.PortableExecutable Imports System.Runtime.InteropServices Imports System.Security.Cryptography Imports System.Text Imports System.Text.RegularExpressions Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.DiaSymReader Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.SharedResourceHelpers Imports Roslyn.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests Partial Public Class CommandLineTests Inherits BasicTestBase Private Shared ReadOnly s_basicCompilerExecutable As String = Path.Combine( Path.GetDirectoryName(GetType(CommandLineTests).Assembly.Location), Path.Combine("dependency", "vbc.exe")) Private Shared ReadOnly s_DotnetCscRun As String = If(ExecutionConditionUtil.IsMono, "mono", String.Empty) Private ReadOnly _baseDirectory As String = TempRoot.Root Private Shared ReadOnly s_defaultSdkDirectory As String = RuntimeEnvironment.GetRuntimeDirectory() Private Shared ReadOnly s_compilerVersion As String = CommonCompiler.GetProductVersion(GetType(CommandLineTests)) Private Shared Function DefaultParse(args As IEnumerable(Of String), baseDirectory As String, Optional sdkDirectory As String = Nothing, Optional additionalReferenceDirectories As String = Nothing) As VisualBasicCommandLineArguments sdkDirectory = If(sdkDirectory, s_defaultSdkDirectory) Return VisualBasicCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories) End Function Private Shared Function FullParse(commandLine As String, baseDirectory As String, Optional sdkDirectory As String = Nothing, Optional additionalReferenceDirectories As String = Nothing) As VisualBasicCommandLineArguments sdkDirectory = If(sdkDirectory, s_defaultSdkDirectory) Dim args = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments:=True) Return VisualBasicCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories) End Function Private Shared Function InteractiveParse(args As IEnumerable(Of String), baseDirectory As String, Optional sdkDirectory As String = Nothing, Optional additionalReferenceDirectories As String = Nothing) As VisualBasicCommandLineArguments sdkDirectory = If(sdkDirectory, s_defaultSdkDirectory) Return VisualBasicCommandLineParser.Script.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories) End Function <Fact> Public Sub SimpleAnalyzerConfig() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.vb").WriteAllText(" Class C Sub M() Dim x As Integer End Sub End Class") Dim additionalFile = dir.CreateFile("file.txt") Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(" [*.vb] dotnet_diagnostic.bc42024.severity = none") Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path}) Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal(0, exitCode) Assert.Equal("", outWriter.ToString()) Assert.Null(cmd.AnalyzerOptions) End Sub <Fact> Public Sub AnalyzerConfigWithOptions() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.vb").WriteAllText(" Class C Sub M() Dim x As Integer End Sub End Class") Dim additionalFile = dir.CreateFile("file.txt") Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(" [*.vb] dotnet_diagnostic.bc42024.severity = none dotnet_diagnostic.warning01.severity = none dotnet_diagnostic.Warning03.severity = none my_option = my_val [*.txt] dotnet_diagnostic.bc42024.severity = none my_option2 = my_val2") Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:42376", "/additionalfile:" + additionalFile.Path, src.Path}) Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal(0, exitCode) Assert.Equal("", outWriter.ToString()) Dim comp = cmd.Compilation Dim tree = comp.SyntaxTrees.Single() Dim syntaxTreeOptions = comp.Options.SyntaxTreeOptionsProvider Dim report As ReportDiagnostic Assert.True(syntaxTreeOptions.TryGetDiagnosticValue(tree, "BC42024", CancellationToken.None, report)) Assert.Equal(ReportDiagnostic.Suppress, report) Assert.True(syntaxTreeOptions.TryGetDiagnosticValue(tree, "warning01", CancellationToken.None, report)) Assert.Equal(ReportDiagnostic.Suppress, report) Assert.True(syntaxTreeOptions.TryGetDiagnosticValue(tree, "warning03", CancellationToken.None, report)) Assert.Equal(ReportDiagnostic.Suppress, report) Assert.False(syntaxTreeOptions.TryGetDiagnosticValue(tree, "warning02", CancellationToken.None, report)) Dim provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider Dim options = provider.GetOptions(tree) Assert.NotNull(options) Dim val As String = Nothing Assert.True(options.TryGetValue("my_option", val)) Assert.Equal("my_val", val) Assert.False(options.TryGetValue("my_option2", Nothing)) Assert.False(options.TryGetValue("dotnet_diagnostic.bc42024.severity", Nothing)) options = provider.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()) Assert.NotNull(options) Assert.True(options.TryGetValue("my_option2", val)) Assert.Equal("my_val2", val) Assert.False(options.TryGetValue("my_option", Nothing)) Assert.False(options.TryGetValue("dotnet_diagnostic.bc42024.severity", Nothing)) End Sub <Fact> Public Sub AnalyzerConfigBadSeverity() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.vb").WriteAllText(" Class C Sub M() Dim x As Integer End Sub End Class") Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(" [*.vb] dotnet_diagnostic.BC42024.severity = garbage") Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path}) Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal(0, exitCode) Assert.Equal( $"vbc : warning InvalidSeverityInAnalyzerConfig: The diagnostic 'bc42024' was given an invalid severity 'garbage' in the analyzer config file at '{analyzerConfig.Path}'. {src.Path}(4) : warning BC42024: Unused local variable: 'x'. Dim x As Integer ~ ", outWriter.ToString()) End Sub <Fact> Public Sub AnalyzerConfigsInSameDir() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.cs").WriteAllText(" Class C Sub M() Dim x As Integer End Sub End Class") Dim configText = " [*.cs] dotnet_diagnostic.cs0169.severity = suppress" Dim analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText) Dim analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText) Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal(1, exitCode) Assert.Equal( $"vbc : error BC42500: Multiple analyzer config files cannot be in the same directory ('{dir.Path}').", outWriter.ToString().TrimEnd()) End Sub <Fact> <WorkItem(34101, "https://github.com/dotnet/roslyn/issues/34101")> Public Sub SuppressedWarnAsErrorsStillEmit() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("temp.vb").WriteAllText(" #Disable Warning BC42302 Module Module1 Sub Main() Dim x = 42 ''' <test /> End Sub End Module") Const docName As String = "doc.xml" Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/errorlog:errorlog", $"/doc:{docName}", "/warnaserror", src.Path}) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal("", outWriter.ToString()) Assert.Equal(0, exitCode) Dim exePath = Path.Combine(dir.Path, "temp.exe") Assert.True(File.Exists(exePath)) End Sub <Fact> Public Sub XmlMemoryMapped() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("temp.cs").WriteAllText(" Class C End Class") Dim docName As String = "doc.xml" Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/t:library", "/preferreduilang:en", $"/doc:{docName}", src.Path}) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal(0, exitCode) Assert.Equal("", outWriter.ToString()) Dim xmlPath = Path.Combine(dir.Path, docName) Using fileStream = New FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) Using mmf = MemoryMappedFile.CreateFromFile(fileStream, "xmlMap", 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen:=True) exitCode = cmd.Run(outWriter) Assert.Equal(1, exitCode) Assert.StartsWith($"vbc : error BC2012: can't open '{xmlPath}' for writing:", outWriter.ToString()) End Using End Using End Sub <Fact> <WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")> Public Sub CompilerBinariesAreAnyCPU() Assert.Equal(ProcessorArchitecture.MSIL, AssemblyName.GetAssemblyName(s_basicCompilerExecutable).ProcessorArchitecture) End Sub <Fact, WorkItem(546322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546322")> Public Sub NowarnWarnaserrorTest() Dim src As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/nowarn", "/warnaserror-", src}) Assert.Equal(cmd.Arguments.CompilationOptions.GeneralDiagnosticOption, ReportDiagnostic.Suppress) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/nowarn", "/warnaserror", src}) Assert.Equal(cmd.Arguments.CompilationOptions.GeneralDiagnosticOption, ReportDiagnostic.Error) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/nowarn", "/warnaserror+", src}) Assert.Equal(cmd.Arguments.CompilationOptions.GeneralDiagnosticOption, ReportDiagnostic.Error) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/warnaserror-", "/nowarn", src}) Assert.Equal(cmd.Arguments.CompilationOptions.GeneralDiagnosticOption, ReportDiagnostic.Suppress) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/warnaserror", "/nowarn", src}) Assert.Equal(cmd.Arguments.CompilationOptions.GeneralDiagnosticOption, ReportDiagnostic.Suppress) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/warnaserror+", "/nowarn", src}) Assert.Equal(cmd.Arguments.CompilationOptions.GeneralDiagnosticOption, ReportDiagnostic.Suppress) CleanupAllGeneratedFiles(src) End Sub <Fact> <WorkItem(21508, "https://github.com/dotnet/roslyn/issues/21508")> Public Sub ArgumentStartWithDashAndContainingSlash() Dim args As VisualBasicCommandLineArguments Dim folder = Temp.CreateDirectory() args = DefaultParse({"-debug+/debug:portable"}, folder.Path) args.Errors.AssertTheseDiagnostics(<errors> BC2007: unrecognized option '-debug+/debug:portable'; ignored BC2008: no input sources specified </errors>) End Sub <WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")> <Fact()> Public Sub CommandLineCompilationWithQuotedMainArgument() ' Arguments with quoted rootnamespace and main type are unquoted when ' the arguments are read in by the command line compiler. Dim src As String = Temp.CreateFile().WriteAllText(<text> Module Module1 Sub Main() End Sub End Module </text>.Value).Path Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/target:exe", "/rootnamespace:""test""", "/main:""test.Module1""", src}) Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) End Sub <Fact> Public Sub CreateCompilationWithKeyFile() Dim source = " Public Class C Public Shared Sub Main() End Sub End Class" Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source) Dim cmd = New MockVisualBasicCompiler(dir.Path, {"/nologo", "a.vb", "/keyfile:key.snk"}) Dim comp = cmd.CreateCompilation(TextWriter.Null, New TouchedFileLogger(), NullErrorLogger.Instance, Nothing) Assert.IsType(Of DesktopStrongNameProvider)(comp.Options.StrongNameProvider) End Sub <Fact> Public Sub CreateCompilationWithCryptoContainer() Dim source = " Public Class C Public Shared Sub Main() End Sub End Class" Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source) Dim cmd = New MockVisualBasicCompiler(dir.Path, {"/nologo", "a.vb", "/keycontainer:aaa"}) Dim comp = cmd.CreateCompilation(TextWriter.Null, New TouchedFileLogger(), NullErrorLogger.Instance, Nothing) Assert.True(TypeOf comp.Options.StrongNameProvider Is DesktopStrongNameProvider) End Sub <Fact> Public Sub CreateCompilationWithStrongNameFallbackCommand() Dim source = " Public Class C Public Shared Sub Main() End Sub End Class" Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source) Dim cmd = New MockVisualBasicCompiler(dir.Path, {"/nologo", "a.vb", "/features:UseLegacyStrongNameProvider"}) Dim comp = cmd.CreateCompilation(TextWriter.Null, New TouchedFileLogger(), NullErrorLogger.Instance, Nothing) Assert.True(TypeOf comp.Options.StrongNameProvider Is DesktopStrongNameProvider) End Sub <Fact> Public Sub ParseQuotedMainTypeAndRootnamespace() 'These options are always unquoted when parsed in VisualBasicCommandLineParser.Parse. Dim args = DefaultParse({"/rootnamespace:Test", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("Test", args.CompilationOptions.RootNamespace) args = DefaultParse({"/main:Test", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("Test", args.CompilationOptions.MainTypeName) args = DefaultParse({"/main:""Test""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("Test", args.CompilationOptions.MainTypeName) args = DefaultParse({"/rootnamespace:""Test""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("Test", args.CompilationOptions.RootNamespace) args = DefaultParse({"/rootnamespace:""test""", "/main:""test.Module1""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("test.Module1", args.CompilationOptions.MainTypeName) Assert.Equal("test", args.CompilationOptions.RootNamespace) ' Use of Cyrillic namespace args = DefaultParse({"/rootnamespace:""решения""", "/main:""решения.Module1""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("решения.Module1", args.CompilationOptions.MainTypeName) Assert.Equal("решения", args.CompilationOptions.RootNamespace) End Sub <WorkItem(722561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722561")> <Fact> Public Sub Bug_722561() Dim src As String = Temp.CreateFile().WriteAllText(<text> Public Class C End Class </text>.Value).Path ' Previous versions of the compiler used to report warnings (BC2026, BC2014) ' whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. ' We no longer generate a warning in such cases. Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/t:library", "/nowarn:-1", src}) Dim writer As New StringWriter() Dim result = cmd.Run(writer, Nothing) Assert.Equal(String.Empty, writer.ToString.Trim) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/t:library", "/nowarn:-12345678901234567890", src}) writer = New StringWriter() result = cmd.Run(writer, Nothing) Assert.Equal(String.Empty, writer.ToString.Trim) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/t:library", "/nowarn:-1234567890123456789", src}) writer = New StringWriter() result = cmd.Run(writer, Nothing) Assert.Equal(String.Empty, writer.ToString.Trim) CleanupAllGeneratedFiles(src) End Sub <Fact> Public Sub VbcTest() Dim output As StringWriter = New StringWriter() Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:en"}) cmd.Run(output, Nothing) Assert.True(output.ToString().StartsWith(s_logoLine1, StringComparison.Ordinal), "vbc should print logo and help if no args specified") End Sub <Fact> Public Sub VbcNologo_1() Dim src As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim output As StringWriter = New StringWriter() Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/t:library", src}) Dim exitCode = cmd.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) CleanupAllGeneratedFiles(src) End Sub <Fact> Public Sub VbcNologo_1a() Dim src As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim output As StringWriter = New StringWriter() Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo+", "/t:library", src}) Dim exitCode = cmd.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) CleanupAllGeneratedFiles(src) End Sub <Fact> Public Sub VbcNologo_2() Dim src As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim output As StringWriter = New StringWriter() Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/preferreduilang:en", src}) Dim exitCode = cmd.Run(output, Nothing) Assert.Equal(0, exitCode) Dim patched As String = Regex.Replace(output.ToString().Trim(), "version \d+\.\d+\.\d+(-[\d\w]+)*", "version A.B.C-d") patched = ReplaceCommitHash(patched) Assert.Equal(<text> Microsoft (R) Visual Basic Compiler version A.B.C-d (HASH) Copyright (C) Microsoft Corporation. All rights reserved. </text>.Value.Replace(vbLf, vbCrLf).Trim, patched) CleanupAllGeneratedFiles(src) End Sub <Theory, InlineData("Microsoft (R) Visual Basic Compiler version A.B.C-d (<developer build>)", "Microsoft (R) Visual Basic Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual Basic Compiler version A.B.C-d (ABCDEF01)", "Microsoft (R) Visual Basic Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual Basic Compiler version A.B.C-d (abcdef90)", "Microsoft (R) Visual Basic Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual Basic Compiler version A.B.C-d (12345678)", "Microsoft (R) Visual Basic Compiler version A.B.C-d (HASH)")> Public Sub TestReplaceCommitHash(orig As String, expected As String) Assert.Equal(expected, ReplaceCommitHash(orig)) End Sub Private Shared Function ReplaceCommitHash(s As String) As String Return Regex.Replace(s, "(\((<developer build>|[a-fA-F0-9]{8})\))", "(HASH)") End Function <Fact> Public Sub VbcNologo_2a() Dim src As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim output As StringWriter = New StringWriter() Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo-", "/preferreduilang:en", "/t:library", src}) Dim exitCode = cmd.Run(output, Nothing) Assert.Equal(0, exitCode) Dim patched As String = Regex.Replace(output.ToString().Trim(), "version \d+\.\d+\.\d+(-[\w\d]+)*", "version A.B.C-d") patched = ReplaceCommitHash(patched) Assert.Equal(<text> Microsoft (R) Visual Basic Compiler version A.B.C-d (HASH) Copyright (C) Microsoft Corporation. All rights reserved. </text>.Value.Replace(vbLf, vbCrLf).Trim, patched) CleanupAllGeneratedFiles(src) End Sub <Fact()> Public Sub VbcUtf8Output_WithRedirecting_Off() Dim src As String = Temp.CreateFile().WriteAllText("♚", New System.Text.UTF8Encoding(False)).Path Dim tempOut = Temp.CreateFile() Dim output = ProcessUtilities.RunAndGetOutput("cmd", "/C """ & s_basicCompilerExecutable & """ /nologo /preferreduilang:en /t:library " & src & " > " & tempOut.Path, expectedRetCode:=1) Assert.Equal("", output.Trim()) Assert.Equal(<text> SRC.VB(1) : error BC30037: Character is not valid. ? ~ </text>.Value.Trim().Replace(vbLf, vbCrLf), tempOut.ReadAllText().Trim().Replace(src, "SRC.VB")) CleanupAllGeneratedFiles(src) End Sub <Fact()> Public Sub VbcUtf8Output_WithRedirecting_On() Dim src As String = Temp.CreateFile().WriteAllText("♚", New System.Text.UTF8Encoding(False)).Path Dim tempOut = Temp.CreateFile() Dim output = ProcessUtilities.RunAndGetOutput("cmd", "/C """ & s_basicCompilerExecutable & """ /utf8output /nologo /preferreduilang:en /t:library " & src & " > " & tempOut.Path, expectedRetCode:=1) Assert.Equal("", output.Trim()) Assert.Equal(<text> SRC.VB(1) : error BC30037: Character is not valid. ♚ ~ </text>.Value.Trim().Replace(vbLf, vbCrLf), tempOut.ReadAllText().Trim().Replace(src, "SRC.VB")) CleanupAllGeneratedFiles(src) End Sub <Fact> Public Sub VbcCompile_WithSourceCodeRedirectedViaStandardInput_ProducesRunnableProgram() Dim result As ProcessResult Dim tempDir As String = Temp.CreateDirectory().Path If RuntimeInformation.IsOSPlatform(OSPlatform.Windows) Then Dim sourceFile = Path.GetTempFileName() File.WriteAllText(sourceFile, " Module Program Sub Main() System.Console.WriteLine(""Hello World!"") End Sub End Module") result = ProcessUtilities.Run("cmd", $"/C {s_basicCompilerExecutable} /nologo /t:exe - < {sourceFile}", workingDirectory:=tempDir) File.Delete(sourceFile) Else result = ProcessUtilities.Run("/usr/bin/env", $"sh -c ""echo \ Module Program \ Sub Main\(\) \ System.Console.WriteLine\(\\\""Hello World\!\\\""\) \ End Sub \ End Module | {s_basicCompilerExecutable} /nologo /t:exe -""", workingDirectory:=tempDir, redirectStandardInput:=True) ' we are testing shell's piped/redirected stdin behavior explicitly ' instead of using Process.StandardInput.Write(), so we set ' redirectStandardInput to true, which implies that isatty of child ' process is false and thereby Console.IsInputRedirected will return ' true in vbc code. End If Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}") Dim output As String = If(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), ProcessUtilities.RunAndGetOutput("cmd.exe", $"/C ""{s_DotnetCscRun} -.exe""", expectedRetCode:=0, startFolder:=tempDir), ProcessUtilities.RunAndGetOutput("sh", $"-c ""{s_DotnetCscRun} -.exe""", expectedRetCode:=0, startFolder:=tempDir)) Assert.Equal("Hello World!", output.Trim()) End Sub <Fact> Public Sub VbcCompile_WithSourceCodeRedirectedViaStandardInput_ProducesLibrary() Dim name = Guid.NewGuid().ToString() & ".dll" Dim tempDir As String = Temp.CreateDirectory().Path Dim result As ProcessResult If RuntimeInformation.IsOSPlatform(OSPlatform.Windows) Then Dim sourceFile = Path.GetTempFileName() File.WriteAllText(sourceFile, " Class A public Function GetVal() As A Return Nothing End Function End Class") result = ProcessUtilities.Run("cmd", $"/C {s_basicCompilerExecutable} /nologo /t:library /out:{name} - < {sourceFile}", workingDirectory:=tempDir) File.Delete(sourceFile) Else result = ProcessUtilities.Run("/usr/bin/env", $"sh -c ""echo \ Class A \ Public Function GetVal\(\) As A \ Return Nothing \ End Function \ End Class | {s_basicCompilerExecutable} /nologo /t:library /out:{name} -""", workingDirectory:=tempDir, redirectStandardInput:=True) ' we are testing shell's piped/redirected stdin behavior explicitly ' instead of using Process.StandardInput.Write(), so we set ' redirectStandardInput to true, which implies that isatty of child ' process is false and thereby Console.IsInputRedirected will return ' true in vbc code. End If Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}") Dim assemblyName = System.Reflection.AssemblyName.GetAssemblyName(Path.Combine(tempDir, name)) Assert.Equal(name.Replace(".dll", ", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), assemblyName.ToString()) End Sub <Fact> Public Sub VbcCompile_WithRedirectedInputIndicatorAndStandardInputNotRedirected_ReportsBC56032() If Console.IsInputRedirected Then ' [applicable to both Windows and Unix] ' if our parent (xunit) process itself has input redirected, we cannot test this ' error case because our child process will inherit it and we cannot achieve what ' we are aiming for: isatty(0):true and thereby Console.IsInputerRedirected:false in ' child. running this case will make StreamReader to hang (waiting for input, that ' we do not propagate: parent.In->child.In). ' ' note: in Unix we can "close" fd0 by appending `0>&-` in the `sh -c` command below, ' but that will also not impact the result of isatty(), and in turn causes a different ' compiler error. Return End If Dim tempDir As String = Temp.CreateDirectory().Path Dim result As ProcessResult = If(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), ProcessUtilities.Run("cmd", $"/C ""{s_basicCompilerExecutable} /nologo /t:exe -""", workingDirectory:=tempDir), ProcessUtilities.Run("/usr/bin/env", $"sh -c ""{s_basicCompilerExecutable} /nologo /t:exe -""", workingDirectory:=tempDir)) Assert.True(result.ContainsErrors) Assert.Contains(CInt(ERRID.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected).ToString(), result.Output) End Sub <Fact()> Public Sub ResponseFiles1() Dim rsp As String = Temp.CreateFile().WriteAllText(<text> /r:System.dll /nostdlib /vbruntime- # this is ignored System.Console.WriteLine(&quot;*?&quot;); # this is error a.vb </text>.Value).Path Dim cmd = New MockVisualBasicCompiler(rsp, _baseDirectory, {"b.vb"}) AssertEx.Equal({"System.dll"}, cmd.Arguments.MetadataReferences.Select(Function(r) r.Reference)) AssertEx.Equal( { Path.Combine(_baseDirectory, "a.vb"), Path.Combine(_baseDirectory, "b.vb") }, cmd.Arguments.SourceFiles.Select(Function(file) file.Path)) Assert.NotEmpty(cmd.Arguments.Errors) CleanupAllGeneratedFiles(rsp) End Sub <WorkItem(685392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685392")> <Fact()> Public Sub ResponseFiles_RootNamespace() Dim rsp As String = Temp.CreateFile().WriteAllText(<text> /r:System.dll /rootnamespace:"Hello" a.vb </text>.Value).Path Dim cmd = New MockVisualBasicCompiler(rsp, _baseDirectory, {"b.vb"}) Assert.Equal("Hello", cmd.Arguments.CompilationOptions.RootNamespace) CleanupAllGeneratedFiles(rsp) End Sub Private Sub AssertGlobalImports(expectedImportStrings As String(), actualImports As GlobalImport()) Assert.Equal(expectedImportStrings.Length, actualImports.Count) For i = 0 To expectedImportStrings.Length - 1 Assert.Equal(expectedImportStrings(i), actualImports(i).Clause.ToString) Next End Sub <Fact> Public Sub ParseGlobalImports() Dim args = DefaultParse({"/imports: System ,System.Xml ,System.Linq", "a.vb"}, _baseDirectory) args.Errors.Verify() AssertEx.Equal({"System", "System.Xml", "System.Linq"}, args.CompilationOptions.GlobalImports.Select(Function(import) import.Clause.ToString())) args = DefaultParse({"/impORt: System,,,,,", "/IMPORTs:,,,Microsoft.VisualBasic,,System.IO", "a.vb"}, _baseDirectory) args.Errors.Verify() AssertEx.Equal({"System", "Microsoft.VisualBasic", "System.IO"}, args.CompilationOptions.GlobalImports.Select(Function(import) import.Clause.ToString())) args = DefaultParse({"/impORt: System, ,, ,,", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_ExpectedIdentifier), Diagnostic(ERRID.ERR_ExpectedIdentifier)) args = DefaultParse({"/impORt:", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("import", ":<str>")) args = DefaultParse({"/impORts:", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("imports", ":<import_list>")) args = DefaultParse({"/imports", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("imports", ":<import_list>")) args = DefaultParse({"/imports+", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/imports+")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact> Public Sub ParseInteractive() Dim args As VisualBasicCommandLineArguments args = DefaultParse({}, _baseDirectory) args.Errors.Verify() Assert.False(args.InteractiveMode) args = DefaultParse({"/i"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/i").WithLocation(1, 1), Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)}) Assert.False(args.InteractiveMode) args = InteractiveParse({}, _baseDirectory) args.Errors.Verify() Assert.True(args.InteractiveMode) args = InteractiveParse({"a.vb"}, _baseDirectory) args.Errors.Verify() Assert.False(args.InteractiveMode) args = InteractiveParse({"/i", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.InteractiveMode) args = InteractiveParse({"/i+", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.InteractiveMode) args = InteractiveParse({"/i+ /i-", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.False(args.InteractiveMode) For Each flag In {"i", "i+", "i-"} args = InteractiveParse({"/" + flag + ":arg"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("i").WithLocation(1, 1)) Next End Sub <Fact> Public Sub ParseInstrumentTestNames() Dim args As VisualBasicCommandLineArguments args = DefaultParse({}, _baseDirectory) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("instrument", ":<string>").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument:""""", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("instrument", ":<string>").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument:", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("instrument", ":<string>").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument:", "Test.Flag.Name", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("instrument", ":<string>").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument:InvalidOption", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument:None", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_InvalidInstrumentationKind).WithArguments("None").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument:""TestCoverage,InvalidOption""", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({InstrumentationKind.TestCoverage})) args = DefaultParse({"/instrument:TestCoverage", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({InstrumentationKind.TestCoverage})) args = DefaultParse({"/instrument:""TestCoverage""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({InstrumentationKind.TestCoverage})) args = DefaultParse({"/instrument:""TESTCOVERAGE""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({InstrumentationKind.TestCoverage})) args = DefaultParse({"/instrument:TestCoverage,TestCoverage", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({InstrumentationKind.TestCoverage})) args = DefaultParse({"/instrument:TestCoverage", "/instrument:TestCoverage", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({InstrumentationKind.TestCoverage})) End Sub <Fact> Public Sub ResponseFiles2() Dim rsp As String = Temp.CreateFile().WriteAllText(<text> /r:System /r:System.Core /r:System.Data /r:System.Data.DataSetExtensions /r:System.Xml /r:System.Xml.Linq /imports:System /imports:System.Collections.Generic /imports:System.Linq /imports:System.Text</text>.Value).Path Dim cmd = New MockVbi(rsp, _baseDirectory, {"b.vbx"}) ' TODO (tomat): mscorlib, vbruntime order 'AssertEx.Equal({GetType(Object).Assembly.Location, ' GetType(Microsoft.VisualBasic.Globals).Assembly.Location, ' "System", "System.Core", "System.Data", "System.Data.DataSetExtensions", "System.Xml", "System.Xml.Linq"}, ' cmd.Arguments.AssemblyReferences.Select(Function(r) ' Return If(r.Kind = ReferenceKind.AssemblyName, ' (DirectCast(r, AssemblyNameReference)).Name, ' (DirectCast(r, AssemblyFileReference)).Path) ' End Function)) AssertEx.Equal({"System", "System.Collections.Generic", "System.Linq", "System.Text"}, cmd.Arguments.CompilationOptions.GlobalImports.Select(Function(import) import.Clause.ToString())) End Sub <Fact, WorkItem(546028, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546028")> Public Sub Win32ResourceArguments() Dim args As String() = {"/win32manifest:..\here\there\everywhere\nonexistent"} Dim parsedArgs = DefaultParse(args, _baseDirectory) Dim compilation = CreateCompilationWithMscorlib40(New VisualBasicSyntaxTree() {}) Dim errors As IEnumerable(Of DiagnosticInfo) = Nothing CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_UnableToReadUacManifest2, Integer), errors.First().Code) Assert.Equal(2, errors.First().Arguments.Count()) args = {"/Win32icon:\bogus"} parsedArgs = DefaultParse(args, _baseDirectory) CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_UnableToOpenResourceFile1, Integer), errors.First().Code) Assert.Equal(2, errors.First().Arguments.Count()) args = {"/Win32Resource:\bogus"} parsedArgs = DefaultParse(args, _baseDirectory) CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_UnableToOpenResourceFile1, Integer), errors.First().Code) Assert.Equal(2, errors.First().Arguments.Count()) args = {"/win32manifest:goo.win32data:bar.win32data2"} parsedArgs = DefaultParse(args, _baseDirectory) CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_UnableToReadUacManifest2, Integer), errors.First().Code) Assert.Equal(2, errors.First().Arguments.Count()) args = {"/Win32icon:goo.win32data:bar.win32data2"} parsedArgs = DefaultParse(args, _baseDirectory) CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_UnableToOpenResourceFile1, Integer), errors.First().Code) Assert.Equal(2, errors.First().Arguments.Count()) args = {"/Win32Resource:goo.win32data:bar.win32data2"} parsedArgs = DefaultParse(args, _baseDirectory) CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_UnableToOpenResourceFile1, Integer), errors.First().Code) Assert.Equal(2, errors.First().Arguments.Count()) End Sub <Fact> Public Sub Win32IconContainsGarbage() Dim tmpFileName As String = Temp.CreateFile().WriteAllBytes(New Byte() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Path Dim parsedArgs = DefaultParse({"/win32icon:" + tmpFileName}, _baseDirectory) Dim compilation = CreateCompilationWithMscorlib40(New VisualBasicSyntaxTree() {}) Dim errors As IEnumerable(Of DiagnosticInfo) = Nothing CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_ErrorCreatingWin32ResourceFile, Integer), errors.First().Code) Assert.Equal(1, errors.First().Arguments.Count()) CleanupAllGeneratedFiles(tmpFileName) End Sub <WorkItem(217718, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=217718")> <Fact> Public Sub BadWin32Resource() Dim source = Temp.CreateFile(prefix:="", extension:=".vb").WriteAllText(" Module Test Sub Main() End Sub End Module").Path Dim badres = Temp.CreateFile().WriteAllBytes(New Byte() {0, 0}).Path Dim baseDir = Path.GetDirectoryName(source) Dim fileName = Path.GetFileName(source) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = New MockVisualBasicCompiler(Nothing, baseDir, { "/nologo", "/preferreduilang:en", "/win32resource:" + badres, source }).Run(outWriter) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC30136: Error creating Win32 resources: Unrecognized resource file format.", outWriter.ToString().Trim()) CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(badres) End Sub <Fact> Public Sub Win32ResourceOptions_Valid() CheckWin32ResourceOptions({"/win32resource:a"}, "a", Nothing, Nothing, False) CheckWin32ResourceOptions({"/win32icon:b"}, Nothing, "b", Nothing, False) CheckWin32ResourceOptions({"/win32manifest:c"}, Nothing, Nothing, "c", False) CheckWin32ResourceOptions({"/nowin32manifest"}, Nothing, Nothing, Nothing, True) End Sub <Fact> Public Sub Win32ResourceOptions_Empty() CheckWin32ResourceOptions({"/win32resource"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32resource", ":<file>")) CheckWin32ResourceOptions({"/win32resource:"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32resource", ":<file>")) CheckWin32ResourceOptions({"/win32resource: "}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32resource", ":<file>")) CheckWin32ResourceOptions({"/win32icon"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32icon", ":<file>")) CheckWin32ResourceOptions({"/win32icon:"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32icon", ":<file>")) CheckWin32ResourceOptions({"/win32icon: "}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32icon", ":<file>")) CheckWin32ResourceOptions({"/win32manifest"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32manifest", ":<file>")) CheckWin32ResourceOptions({"/win32manifest:"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32manifest", ":<file>")) CheckWin32ResourceOptions({"/win32manifest: "}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32manifest", ":<file>")) CheckWin32ResourceOptions({"/nowin32manifest"}, Nothing, Nothing, Nothing, True) CheckWin32ResourceOptions({"/nowin32manifest:"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/nowin32manifest:")) CheckWin32ResourceOptions({"/nowin32manifest: "}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/nowin32manifest:")) End Sub <Fact> Public Sub Win32ResourceOptions_Combinations() ' last occurrence wins CheckWin32ResourceOptions({"/win32resource:r", "/win32resource:s"}, "s", Nothing, Nothing, False) ' illegal CheckWin32ResourceOptions({"/win32resource:r", "/win32icon:i"}, "r", "i", Nothing, False, Diagnostic(ERRID.ERR_IconFileAndWin32ResFile)) ' documented as illegal, but works in dev10 CheckWin32ResourceOptions({"/win32resource:r", "/win32manifest:m"}, "r", Nothing, "m", False, Diagnostic(ERRID.ERR_CantHaveWin32ResAndManifest)) ' fine CheckWin32ResourceOptions({"/win32resource:r", "/nowin32manifest"}, "r", Nothing, Nothing, True) ' illegal CheckWin32ResourceOptions({"/win32icon:i", "/win32resource:r"}, "r", "i", Nothing, False, Diagnostic(ERRID.ERR_IconFileAndWin32ResFile)) ' last occurrence wins CheckWin32ResourceOptions({"/win32icon:i", "/win32icon:j"}, Nothing, "j", Nothing, False) ' fine CheckWin32ResourceOptions({"/win32icon:i", "/win32manifest:m"}, Nothing, "i", "m", False) ' fine CheckWin32ResourceOptions({"/win32icon:i", "/nowin32manifest"}, Nothing, "i", Nothing, True) ' documented as illegal, but works in dev10 CheckWin32ResourceOptions({"/win32manifest:m", "/win32resource:r"}, "r", Nothing, "m", False, Diagnostic(ERRID.ERR_CantHaveWin32ResAndManifest)) ' fine CheckWin32ResourceOptions({"/win32manifest:m", "/win32icon:i"}, Nothing, "i", "m", False) ' last occurrence wins CheckWin32ResourceOptions({"/win32manifest:m", "/win32manifest:n"}, Nothing, Nothing, "n", False) ' illegal CheckWin32ResourceOptions({"/win32manifest:m", "/nowin32manifest"}, Nothing, Nothing, "m", True, Diagnostic(ERRID.ERR_ConflictingManifestSwitches)) ' fine CheckWin32ResourceOptions({"/nowin32manifest", "/win32resource:r"}, "r", Nothing, Nothing, True) ' fine CheckWin32ResourceOptions({"/nowin32manifest", "/win32icon:i"}, Nothing, "i", Nothing, True) ' illegal CheckWin32ResourceOptions({"/nowin32manifest", "/win32manifest:m"}, Nothing, Nothing, "m", True, Diagnostic(ERRID.ERR_ConflictingManifestSwitches)) ' fine CheckWin32ResourceOptions({"/nowin32manifest", "/nowin32manifest"}, Nothing, Nothing, Nothing, True) End Sub <Fact> Public Sub Win32ResourceOptions_SimplyInvalid() Dim parsedArgs = DefaultParse({"/win32resource", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32resource", ":<file>")) parsedArgs = DefaultParse({"/win32resource+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/win32resource+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/win32resource-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/win32resource-")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/win32icon", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32icon", ":<file>")) parsedArgs = DefaultParse({"/win32icon+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/win32icon+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/win32icon-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/win32icon-")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/win32manifest", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32manifest", ":<file>")) parsedArgs = DefaultParse({"/win32manifest+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/win32manifest+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/win32manifest-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/win32manifest-")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub Private Sub CheckWin32ResourceOptions(args As String(), expectedResourceFile As String, expectedIcon As String, expectedManifest As String, expectedNoManifest As Boolean, ParamArray diags As DiagnosticDescription()) Dim parsedArgs = DefaultParse(args.Concat({"Test.vb"}), _baseDirectory) parsedArgs.Errors.Verify(diags) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(expectedResourceFile, parsedArgs.Win32ResourceFile) Assert.Equal(expectedIcon, parsedArgs.Win32Icon) Assert.Equal(expectedManifest, parsedArgs.Win32Manifest) Assert.Equal(expectedNoManifest, parsedArgs.NoWin32Manifest) End Sub <Fact> Public Sub ParseResourceDescription() Dim diags = New List(Of Diagnostic)() Dim desc As ResourceDescription desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someFile.goo.bar", desc.ResourceName) Assert.True(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,someName", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someName", desc.ResourceName) Assert.True(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,someName,public", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someName", desc.ResourceName) Assert.True(desc.IsPublic) ' use file name in place of missing resource name desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,,private", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someFile.goo.bar", desc.ResourceName) Assert.False(desc.IsPublic) ' quoted accessibility is fine desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,,""private""", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someFile.goo.bar", desc.ResourceName) Assert.False(desc.IsPublic) ' leading commas are ignored... desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", ",,\somepath\someFile.goo.bar,,private", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someFile.goo.bar", desc.ResourceName) Assert.False(desc.IsPublic) ' ...as long as there's no whitespace between them desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", ", ,\somepath\someFile.goo.bar,,private", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) ' trailing commas are ignored... desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,,private", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someFile.goo.bar", desc.ResourceName) Assert.False(desc.IsPublic) ' ...even if there's whitespace between them desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,,private, ,", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someFile.goo.bar", desc.ResourceName) Assert.False(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,someName,publi", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", "publi")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "D:rive\relative\path,someName,public", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("D:rive\relative\path")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "inva\l*d?path,someName,public", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("inva\l*d?path")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", Nothing, _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("resource", ":<resinfo>")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("resource", ":<resinfo>")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " ", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " , ", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "path, ", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("path", desc.FileName) Assert.Equal("path", desc.ResourceName) Assert.True(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " ,name", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " , , ", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "path, , ", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " ,name, ", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " , ,private", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "path,name,", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("path", desc.FileName) Assert.Equal("name", desc.ResourceName) Assert.True(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "path,name,,", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("path", desc.FileName) Assert.Equal("name", desc.ResourceName) Assert.True(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "path,name, ", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "path, ,private", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("path", desc.FileName) Assert.Equal("path", desc.ResourceName) Assert.False(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " ,name,private", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) Dim longI = New String("i"c, 260) desc = VisualBasicCommandLineParser.ParseResourceDescription("", String.Format("{0},e,private", longI), _baseDirectory, diags, embedded:=False) ' // error BC2032: File name 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long diags.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii").WithLocation(1, 1)) End Sub <Fact> Public Sub ManagedResourceOptions() Dim parsedArgs As VisualBasicCommandLineArguments Dim resourceDescription As ResourceDescription parsedArgs = DefaultParse({"/resource:a", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.DisplayHelp) resourceDescription = parsedArgs.ManifestResources.Single() Assert.Null(resourceDescription.FileName) ' since embedded Assert.Equal("a", resourceDescription.ResourceName) parsedArgs = DefaultParse({"/res:b", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.DisplayHelp) resourceDescription = parsedArgs.ManifestResources.Single() Assert.Null(resourceDescription.FileName) ' since embedded Assert.Equal("b", resourceDescription.ResourceName) parsedArgs = DefaultParse({"/linkresource:c", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.DisplayHelp) resourceDescription = parsedArgs.ManifestResources.Single() Assert.Equal("c", resourceDescription.FileName) Assert.Equal("c", resourceDescription.ResourceName) parsedArgs = DefaultParse({"/linkres:d", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.DisplayHelp) resourceDescription = parsedArgs.ManifestResources.Single() Assert.Equal("d", resourceDescription.FileName) Assert.Equal("d", resourceDescription.ResourceName) End Sub <Fact> Public Sub ManagedResourceOptions_SimpleErrors() Dim parsedArgs = DefaultParse({"/resource:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("resource", ":<resinfo>")) parsedArgs = DefaultParse({"/resource: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("resource", ":<resinfo>")) parsedArgs = DefaultParse({"/resource", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("resource", ":<resinfo>")) parsedArgs = DefaultParse({"/RES+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/RES+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/res-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/res-:")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/linkresource:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("linkresource", ":<resinfo>")) parsedArgs = DefaultParse({"/linkresource: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("linkresource", ":<resinfo>")) parsedArgs = DefaultParse({"/linkresource", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("linkresource", ":<resinfo>")) parsedArgs = DefaultParse({"/linkRES+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/linkRES+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/linkres-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/linkres-:")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact> Public Sub ModuleManifest() Dim parsedArgs = DefaultParse({"/win32manifest:blah", "/target:module", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_IgnoreModuleManifest)) ' Illegal, but not clobbered. Assert.Equal("blah", parsedArgs.Win32Manifest) End Sub <Fact> Public Sub ArgumentParsing() Dim parsedArgs = InteractiveParse({"a + b"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(True, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"a + b; c"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(True, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"/help"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(True, parsedArgs.DisplayHelp) Assert.Equal(False, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"/version"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.True(parsedArgs.DisplayVersion) Assert.Equal(False, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"/version", "c"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.True(parsedArgs.DisplayVersion) Assert.Equal(True, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"/version:something"}, _baseDirectory) Assert.Equal(True, parsedArgs.Errors.Any()) Assert.False(parsedArgs.DisplayVersion) parsedArgs = InteractiveParse({"/?"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(True, parsedArgs.DisplayHelp) Assert.Equal(False, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"@dd"}, _baseDirectory) Assert.Equal(True, parsedArgs.Errors.Any()) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(False, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"c /define:DEBUG"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(True, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"\\"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".exe")) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(True, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"""/r d.dll"""}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(True, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"/r: d.dll"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(False, parsedArgs.SourceFiles.Any()) End Sub <Fact> Public Sub LangVersion() Dim parsedArgs = DefaultParse({"/langversion:9", "a.VB"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic9, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:9.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic9, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:10", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic10, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:10.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic10, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:11", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic11, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:11.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic11, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:12", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic12, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:12.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic12, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:14", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic14, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:14.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic14, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:15", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic15, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:15.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic15, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:15.3", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic15_3, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:15.5", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic15_5, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:16", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic16, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:16.9", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic16_9, parsedArgs.ParseOptions.LanguageVersion) ' The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary() parsedArgs = DefaultParse({"/langVERSION:default", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion) Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:latest", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.Latest, parsedArgs.ParseOptions.SpecifiedLanguageVersion) Assert.Equal(LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) ' default: "current version" parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) ' overriding parsedArgs = DefaultParse({"/langVERSION:10", "/langVERSION:9.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic9, parsedArgs.ParseOptions.LanguageVersion) ' errors parsedArgs = DefaultParse({"/langVERSION", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("langversion", ":<number>")) Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/langVERSION+")) ' TODO: Dev11 reports ERR_ArgumentRequired Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("langversion", ":<number>")) Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:8", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("langversion", "8")) Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:" & (LanguageVersion.VisualBasic12 + 1), "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("langversion", CStr(LanguageVersion.VisualBasic12 + 1))) Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) End Sub <Fact> Public Sub DelaySign() Dim parsedArgs = DefaultParse({"/delaysign", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.NotNull(parsedArgs.CompilationOptions.DelaySign) Assert.Equal(True, parsedArgs.CompilationOptions.DelaySign) parsedArgs = DefaultParse({"/delaysign+", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.NotNull(parsedArgs.CompilationOptions.DelaySign) Assert.Equal(True, parsedArgs.CompilationOptions.DelaySign) parsedArgs = DefaultParse({"/DELAYsign-", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.NotNull(parsedArgs.CompilationOptions.DelaySign) Assert.Equal(False, parsedArgs.CompilationOptions.DelaySign) parsedArgs = DefaultParse({"/delaysign:-", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("delaysign")) parsedArgs = InteractiveParse({"/d:a=1"}, _baseDirectory) ' test default value parsedArgs.Errors.Verify() Assert.Null(parsedArgs.CompilationOptions.DelaySign) End Sub <WorkItem(546113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546113")> <Fact> Public Sub OutputVerbose() Dim parsedArgs = DefaultParse({"/verbose", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Verbose, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/verbose+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Verbose, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/verbose-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Normal, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/VERBOSE:-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/VERBOSE:-")) parsedArgs = DefaultParse({"/verbose-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("verbose")) parsedArgs = DefaultParse({"/verbose+:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("verbose")) parsedArgs = DefaultParse({"/verbOSE:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/verbOSE:")) parsedArgs = InteractiveParse({"/d:a=1"}, _baseDirectory) ' test default value parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Normal, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/quiet", "/verbose", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Verbose, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/quiet", "/verbose-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Normal, parsedArgs.OutputLevel) End Sub <WorkItem(546113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546113")> <Fact> Public Sub OutputQuiet() Dim parsedArgs = DefaultParse({"/quiet", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Quiet, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/quiet+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Quiet, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/quiet-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Normal, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/QUIET:-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/QUIET:-")) parsedArgs = DefaultParse({"/quiet-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("quiet")) parsedArgs = DefaultParse({"/quiet+:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("quiet")) parsedArgs = DefaultParse({"/quiET:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/quiET:")) parsedArgs = InteractiveParse({"/d:a=1"}, _baseDirectory) ' test default value parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Normal, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/verbose", "/quiet", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Quiet, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/verbose", "/quiet-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Normal, parsedArgs.OutputLevel) End Sub <Fact> Public Sub Optimize() Dim parsedArgs = DefaultParse({"/optimize", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel) parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel) ' default parsedArgs = DefaultParse({"/OPTIMIZE+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel) parsedArgs = DefaultParse({"/optimize-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel) parsedArgs = DefaultParse({"/optimize-", "/optimize+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel) parsedArgs = DefaultParse({"/OPTIMIZE:", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optimize")) parsedArgs = DefaultParse({"/OPTIMIZE+:", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optimize")) parsedArgs = DefaultParse({"/optimize-:", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optimize")) End Sub <WorkItem(5417, "DevDiv")> <Fact> Public Sub Deterministic() Dim ParsedArgs = DefaultParse({"a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.Equal(False, ParsedArgs.CompilationOptions.Deterministic) ParsedArgs = DefaultParse({"/deterministic+", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.Equal(True, ParsedArgs.CompilationOptions.Deterministic) ParsedArgs = DefaultParse({"/deterministic", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.Equal(True, ParsedArgs.CompilationOptions.Deterministic) ParsedArgs = DefaultParse({"/DETERMINISTIC+", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.Equal(True, ParsedArgs.CompilationOptions.Deterministic) ParsedArgs = DefaultParse({"/deterministic-", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.Equal(False, ParsedArgs.CompilationOptions.Deterministic) End Sub <WorkItem(546301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546301")> <Fact> Public Sub Parallel() Dim parsedArgs = DefaultParse({"/parallel", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/p", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) ' default parsedArgs = DefaultParse({"/PARALLEL+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/PARALLEL-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/PArallel-", "/PArallel+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/parallel:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("parallel")) parsedArgs = DefaultParse({"/parallel+:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("parallel")) parsedArgs = DefaultParse({"/parallel-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("parallel")) parsedArgs = DefaultParse({"/P+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/P-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/P-", "/P+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/p:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("p")) parsedArgs = DefaultParse({"/p+:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("p")) parsedArgs = DefaultParse({"/p-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("p")) End Sub <Fact> Public Sub SubsystemVersionTests() Dim parsedArgs = DefaultParse({"/subsystemversion:4.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(SubsystemVersion.Create(4, 0), parsedArgs.EmitOptions.SubsystemVersion) ' wrongly supported subsystem version. CompilationOptions data will be faithful to the user input. ' It is normalized at the time of emit. parsedArgs = DefaultParse({"/subsystemversion:0.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() ' no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion) parsedArgs = DefaultParse({"/subsystemversion:0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() ' no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion) parsedArgs = DefaultParse({"/subsystemversion:3.99", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() ' no warning in Dev11 Assert.Equal(SubsystemVersion.Create(3, 99), parsedArgs.EmitOptions.SubsystemVersion) parsedArgs = DefaultParse({"/subsystemversion:4.0", "/subsystemversion:5.333", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(SubsystemVersion.Create(5, 333), parsedArgs.EmitOptions.SubsystemVersion) parsedArgs = DefaultParse({"/subsystemversion:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("subsystemversion", ":<version>")) parsedArgs = DefaultParse({"/subsystemversion", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("subsystemversion", ":<version>")) parsedArgs = DefaultParse({"/subsystemversion-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/subsystemversion-")) ' TODO: Dev11 reports ERRID.ERR_ArgumentRequired parsedArgs = DefaultParse({"/subsystemversion: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("subsystemversion", ":<version>")) parsedArgs = DefaultParse({"/subsystemversion: 4.1", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments(" 4.1")) parsedArgs = DefaultParse({"/subsystemversion:4 .0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("4 .0")) parsedArgs = DefaultParse({"/subsystemversion:4. 0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("4. 0")) parsedArgs = DefaultParse({"/subsystemversion:.", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments(".")) parsedArgs = DefaultParse({"/subsystemversion:4.", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("4.")) parsedArgs = DefaultParse({"/subsystemversion:.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments(".0")) parsedArgs = DefaultParse({"/subsystemversion:4.2 ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/subsystemversion:4.65536", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("4.65536")) parsedArgs = DefaultParse({"/subsystemversion:65536.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("65536.0")) parsedArgs = DefaultParse({"/subsystemversion:-4.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("-4.0")) ' TODO: incompatibilities: versions lower than '6.2' and 'arm', 'winmdobj', 'appcontainer' End Sub <Fact> Public Sub Codepage() Dim parsedArgs = DefaultParse({"/CodePage:1200", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("Unicode", parsedArgs.Encoding.EncodingName) parsedArgs = DefaultParse({"/CodePage:1200", "/CodePage:65001", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("Unicode (UTF-8)", parsedArgs.Encoding.EncodingName) ' errors parsedArgs = DefaultParse({"/codepage:0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadCodepage).WithArguments("0")) parsedArgs = DefaultParse({"/codepage:abc", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadCodepage).WithArguments("abc")) parsedArgs = DefaultParse({"/codepage:-5", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadCodepage).WithArguments("-5")) parsedArgs = DefaultParse({"/codepage: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("codepage", ":<number>")) parsedArgs = DefaultParse({"/codepage:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("codepage", ":<number>")) parsedArgs = DefaultParse({"/codepage+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/codepage+")) ' Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/codepage", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("codepage", ":<number>")) End Sub <Fact, WorkItem(24735, "https://github.com/dotnet/roslyn/issues/24735")> Public Sub ChecksumAlgorithm() Dim parsedArgs As VisualBasicCommandLineArguments parsedArgs = DefaultParse({"/checksumAlgorithm:sHa1", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(SourceHashAlgorithm.Sha1, parsedArgs.ChecksumAlgorithm) Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm) parsedArgs = DefaultParse({"/checksumAlgorithm:sha256", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm) Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm) parsedArgs = DefaultParse({"a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm) Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm) ' error parsedArgs = DefaultParse({"/checksumAlgorithm:256", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadChecksumAlgorithm).WithArguments("256")) parsedArgs = DefaultParse({"/checksumAlgorithm:sha-1", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadChecksumAlgorithm).WithArguments("sha-1")) parsedArgs = DefaultParse({"/checksumAlgorithm:sha", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadChecksumAlgorithm).WithArguments("sha")) parsedArgs = DefaultParse({"/checksumAlgorithm: ", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("checksumalgorithm", ":<algorithm>")) parsedArgs = DefaultParse({"/checksumAlgorithm:", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("checksumalgorithm", ":<algorithm>")) parsedArgs = DefaultParse({"/checksumAlgorithm", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("checksumalgorithm", ":<algorithm>")) parsedArgs = DefaultParse({"/checksumAlgorithm+", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/checksumAlgorithm+")) End Sub <Fact> Public Sub MainTypeName() Dim parsedArgs = DefaultParse({"/main:A.B.C", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("A.B.C", parsedArgs.CompilationOptions.MainTypeName) ' overriding the value parsedArgs = DefaultParse({"/Main:A.B.C", "/M:X.Y.Z", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("X.Y.Z", parsedArgs.CompilationOptions.MainTypeName) parsedArgs = DefaultParse({"/MAIN: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("main", ":<class>")) Assert.Null(parsedArgs.CompilationOptions.MainTypeName) ' EDMAURER Dev11 accepts and MainTypeName is " " ' errors parsedArgs = DefaultParse({"/maiN:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("main", ":<class>")) parsedArgs = DefaultParse({"/m", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("m", ":<class>")) parsedArgs = DefaultParse({"/m+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/m+")) ' Dev11 reports ERR_ArgumentRequired ' incompatibilities ignored by Dev11 parsedArgs = DefaultParse({"/MAIN:XYZ", "/t:library", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("XYZ", parsedArgs.CompilationOptions.MainTypeName) Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/MAIN:XYZ", "/t:module", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind) End Sub <Fact> Public Sub OptionCompare() Dim parsedArgs = InteractiveParse({"/optioncompare"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Length) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("optioncompare", ":binary|text")) Assert.Equal(False, parsedArgs.CompilationOptions.OptionCompareText) parsedArgs = InteractiveParse({"/optioncompare:text", "/optioncompare"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Length) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("optioncompare", ":binary|text")) Assert.Equal(True, parsedArgs.CompilationOptions.OptionCompareText) parsedArgs = InteractiveParse({"/opTioncompare:Text", "/optioncomparE:bINARY"}, _baseDirectory) Assert.Equal(0, parsedArgs.Errors.Length) Assert.Equal(False, parsedArgs.CompilationOptions.OptionCompareText) parsedArgs = InteractiveParse({"/d:a=1"}, _baseDirectory) ' test default value Assert.Equal(0, parsedArgs.Errors.Length) Assert.Equal(False, parsedArgs.CompilationOptions.OptionCompareText) End Sub <Fact> Public Sub OptionExplicit() Dim parsedArgs = InteractiveParse({"/optiONexplicit"}, _baseDirectory) Assert.Equal(0, parsedArgs.Errors.Length) Assert.Equal(True, parsedArgs.CompilationOptions.OptionExplicit) parsedArgs = InteractiveParse({"/optiONexplicit:+"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Length) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optionexplicit")) Assert.Equal(True, parsedArgs.CompilationOptions.OptionExplicit) parsedArgs = InteractiveParse({"/optiONexplicit-:"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Length) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optionexplicit")) parsedArgs = InteractiveParse({"/optionexplicit+", "/optiONexplicit-:"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Length) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optionexplicit")) parsedArgs = InteractiveParse({"/optionexplicit+", "/optiONexplicit-", "/optiONexpliCIT+"}, _baseDirectory) Assert.Equal(0, parsedArgs.Errors.Length) Assert.Equal(True, parsedArgs.CompilationOptions.OptionExplicit) parsedArgs = InteractiveParse({"/d:a=1"}, _baseDirectory) ' test default value Assert.Equal(0, parsedArgs.Errors.Length) Assert.Equal(True, parsedArgs.CompilationOptions.OptionExplicit) End Sub <Fact> Public Sub OptionInfer() Dim parsedArgs = InteractiveParse({"/optiONinfer"}, _baseDirectory) Assert.Equal(0, parsedArgs.Errors.Length) Assert.Equal(True, parsedArgs.CompilationOptions.OptionInfer) parsedArgs = InteractiveParse({"/OptionInfer:+"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optioninfer")) parsedArgs = InteractiveParse({"/OPTIONinfer-:"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optioninfer")) parsedArgs = InteractiveParse({"/optioninfer+", "/optioninFER-:"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optioninfer")) parsedArgs = InteractiveParse({"/optioninfer+", "/optioninfeR-", "/OptionInfer+"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.OptionInfer) parsedArgs = InteractiveParse({"/d:a=1"}, _baseDirectory) ' test default value parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.CompilationOptions.OptionInfer) End Sub Private ReadOnly s_VBC_VER As Double = PredefinedPreprocessorSymbols.CurrentVersionNumber <Fact> Public Sub LanguageVersionAdded_Canary() ' When a new version is added, this test will break. This list must be checked: ' - update the "UpgradeProject" codefixer (not yet supported in VB) ' - update all the tests that call this canary ' - update the command-line documentation (CommandLine.md) AssertEx.SetEqual({"default", "9", "10", "11", "12", "14", "15", "15.3", "15.5", "16", "16.9", "latest"}, System.Enum.GetValues(GetType(LanguageVersion)).Cast(Of LanguageVersion)().Select(Function(v) v.ToDisplayString())) ' For minor versions, the format should be "x.y", such as "15.3" End Sub <Fact> Public Sub LanguageVersion_GetErrorCode() Dim versions = System.Enum.GetValues(GetType(LanguageVersion)). Cast(Of LanguageVersion)(). Except({LanguageVersion.Default, LanguageVersion.Latest}). Select(Function(v) v.GetErrorName()) Dim errorCodes = { "9.0", "10.0", "11.0", "12.0", "14.0", "15.0", "15.3", "15.5", "16", "16.9" } AssertEx.SetEqual(versions, errorCodes) ' The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary() End Sub <Fact> Public Sub LanguageVersion_MapSpecifiedToEffectiveVersion() Assert.Equal(LanguageVersion.VisualBasic9, LanguageVersion.VisualBasic9.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic10, LanguageVersion.VisualBasic10.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic11, LanguageVersion.VisualBasic11.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic12, LanguageVersion.VisualBasic12.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic14, LanguageVersion.VisualBasic14.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic15, LanguageVersion.VisualBasic15.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic15_3, LanguageVersion.VisualBasic15_3.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic15_5, LanguageVersion.VisualBasic15_5.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic16, LanguageVersion.VisualBasic16.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic16_9, LanguageVersion.VisualBasic16_9.MapSpecifiedToEffectiveVersion()) ' The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary() End Sub <Theory, InlineData("9", True, LanguageVersion.VisualBasic9), InlineData("9.0", True, LanguageVersion.VisualBasic9), InlineData("10", True, LanguageVersion.VisualBasic10), InlineData("10.0", True, LanguageVersion.VisualBasic10), InlineData("11", True, LanguageVersion.VisualBasic11), InlineData("11.0", True, LanguageVersion.VisualBasic11), InlineData("12", True, LanguageVersion.VisualBasic12), InlineData("12.0", True, LanguageVersion.VisualBasic12), InlineData("14", True, LanguageVersion.VisualBasic14), InlineData("14.0", True, LanguageVersion.VisualBasic14), InlineData("15", True, LanguageVersion.VisualBasic15), InlineData("15.0", True, LanguageVersion.VisualBasic15), InlineData("15.3", True, LanguageVersion.VisualBasic15_3), InlineData("15.5", True, LanguageVersion.VisualBasic15_5), InlineData("16", True, LanguageVersion.VisualBasic16), InlineData("16.0", True, LanguageVersion.VisualBasic16), InlineData("16.9", True, LanguageVersion.VisualBasic16_9), InlineData("DEFAULT", True, LanguageVersion.Default), InlineData("default", True, LanguageVersion.Default), InlineData("LATEST", True, LanguageVersion.Latest), InlineData("latest", True, LanguageVersion.Latest), InlineData(Nothing, False, LanguageVersion.Default), InlineData("bad", False, LanguageVersion.Default)> Public Sub LanguageVersion_TryParseDisplayString(input As String, success As Boolean, expected As LanguageVersion) Dim version As LanguageVersion Assert.Equal(success, TryParse(input, version)) Assert.Equal(expected, version) ' The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary() End Sub <Fact> Public Sub LanguageVersion_ListLangVersions() Dim dir = Temp.CreateDirectory() Dim outWriter As New StringWriter() Dim exitCode As Integer = New MockVisualBasicCompiler(Nothing, dir.ToString(), {"/langversion:?"}).Run(outWriter, Nothing) Assert.Equal(0, exitCode) Dim actual = outWriter.ToString() Dim expected = [Enum].GetValues(GetType(LanguageVersion)).Cast(Of LanguageVersion)().Select(Function(v) v.ToDisplayString()) Dim acceptableSurroundingChar = {CChar(vbCr), CChar(vbLf), "("c, ")"c, " "c} For Each v In expected Dim foundIndex = actual.IndexOf(v) Assert.True(foundIndex > 0, $"Missing version '{v}'") Assert.True(Array.IndexOf(acceptableSurroundingChar, actual(foundIndex - 1)) >= 0) Assert.True(Array.IndexOf(acceptableSurroundingChar, actual(foundIndex + v.Length)) >= 0) Next End Sub <Fact> Public Sub TestDefine() TestDefines({"/D:a=True,b=1", "a.vb"}, {"a", True}, {"b", 1}, {"TARGET", "exe"}, {"VBC_VER", s_VBC_VER}) TestDefines({"/D:a=True,b=1", "/define:a=""123"",b=False", "a.vb"}, {"a", "123"}, {"b", False}, {"TARGET", "exe"}, {"VBC_VER", s_VBC_VER}) TestDefines({"/D:a=""\\\\a"",b=""\\\\\b""", "a.vb"}, {"a", "\\\\a"}, {"b", "\\\\\b"}, {"TARGET", "exe"}, {"VBC_VER", s_VBC_VER}) TestDefines({"/define:DEBUG", "a.vb"}, {"DEBUG", True}, {"TARGET", "exe"}, {"VBC_VER", s_VBC_VER}) TestDefines({"/D:TARGET=True,VBC_VER=1", "a.vb"}, {"TARGET", True}, {"VBC_VER", 1}) End Sub Private Sub TestDefines(args As IEnumerable(Of String), ParamArray symbols As Object()()) Dim parsedArgs = DefaultParse(args, _baseDirectory) Assert.False(parsedArgs.Errors.Any) Assert.Equal(symbols.Length, parsedArgs.ParseOptions.PreprocessorSymbols.Length) Dim sortedDefines = parsedArgs.ParseOptions. PreprocessorSymbols.Select( Function(d) New With {d.Key, d.Value}).OrderBy(Function(o) o.Key) For i = 0 To symbols.Length - 1 Assert.Equal(symbols(i)(0), sortedDefines(i).Key) Assert.Equal(symbols(i)(1), sortedDefines(i).Value) Next End Sub <Fact> Public Sub OptionStrict() Dim parsedArgs = DefaultParse({"/optionStrict", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(VisualBasic.OptionStrict.On, parsedArgs.CompilationOptions.OptionStrict) parsedArgs = DefaultParse({"/optionStrict+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(VisualBasic.OptionStrict.On, parsedArgs.CompilationOptions.OptionStrict) parsedArgs = DefaultParse({"/optionStrict-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(VisualBasic.OptionStrict.Off, parsedArgs.CompilationOptions.OptionStrict) parsedArgs = DefaultParse({"/OptionStrict:cusTom", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(VisualBasic.OptionStrict.Custom, parsedArgs.CompilationOptions.OptionStrict) parsedArgs = DefaultParse({"/OptionStrict:cusTom", "/optionstrict-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(VisualBasic.OptionStrict.Off, parsedArgs.CompilationOptions.OptionStrict) parsedArgs = DefaultParse({"/optionstrict-", "/OptionStrict:cusTom", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(VisualBasic.OptionStrict.Custom, parsedArgs.CompilationOptions.OptionStrict) parsedArgs = DefaultParse({"/optionstrict:", "/OptionStrict:cusTom", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("optionstrict", ":custom")) parsedArgs = DefaultParse({"/optionstrict:xxx", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("optionstrict", ":custom")) End Sub <WorkItem(546319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546319")> <WorkItem(546318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546318")> <WorkItem(685392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685392")> <Fact> Public Sub RootNamespace() Dim parsedArgs = DefaultParse({"/rootnamespace:One.Two.Three", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("One.Two.Three", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace:One Two Three", "/rootnamespace:One.Two.Three", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("One.Two.Three", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace:""One.Two.Three""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("One.Two.Three", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("rootnamespace", ":<string>")) parsedArgs = DefaultParse({"/rootnamespace:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("rootnamespace", ":<string>")) parsedArgs = DefaultParse({"/rootnamespace+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/rootnamespace+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/rootnamespace-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/rootnamespace-:")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/rootnamespace:+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("+")) parsedArgs = DefaultParse({"/rootnamespace: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("rootnamespace", ":<string>")) parsedArgs = DefaultParse({"/rootnamespace: A.B.C", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments(" A.B.C")) parsedArgs = DefaultParse({"/rootnamespace:[abcdef", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("[abcdef")) parsedArgs = DefaultParse({"/rootnamespace:abcdef]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("abcdef]")) parsedArgs = DefaultParse({"/rootnamespace:[[abcdef]]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("[[abcdef]]")) parsedArgs = DefaultParse({"/rootnamespace:[global]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("[global]", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace:goo.[global].bar", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("goo.[global].bar", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace:goo.[bar]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("goo.[bar]", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace:goo$", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("goo$")) parsedArgs = DefaultParse({"/rootnamespace:I(", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("I(")) parsedArgs = DefaultParse({"/rootnamespace:_", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("_")) parsedArgs = DefaultParse({"/rootnamespace:[_]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("[_]")) parsedArgs = DefaultParse({"/rootnamespace:__.___", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("__.___", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace:[", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("[")) parsedArgs = DefaultParse({"/rootnamespace:]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("]")) parsedArgs = DefaultParse({"/rootnamespace:[]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("[]")) End Sub <Fact> Public Sub Link_SimpleTests() Dim parsedArgs = DefaultParse({"/link:a", "/link:b,,,,c", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal({"a", "b", "c"}, parsedArgs.MetadataReferences. Where(Function(res) res.Properties.EmbedInteropTypes). Select(Function(res) res.Reference)) parsedArgs = DefaultParse({"/Link: ,,, b ,,", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal({" ", " b "}, parsedArgs.MetadataReferences. Where(Function(res) res.Properties.EmbedInteropTypes). Select(Function(res) res.Reference)) parsedArgs = DefaultParse({"/l:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("l", ":<file_list>")) parsedArgs = DefaultParse({"/L", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("l", ":<file_list>")) parsedArgs = DefaultParse({"/l+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/l+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/link-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/link-:")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact> Public Sub Recurse_SimpleTests() Dim dir = Temp.CreateDirectory() Dim file1 = dir.CreateFile("a.vb") Dim file2 = dir.CreateFile("b.vb") Dim file3 = dir.CreateFile("c.txt") Dim file4 = dir.CreateDirectory("d1").CreateFile("d.txt") Dim file5 = dir.CreateDirectory("d2").CreateFile("e.vb") file1.WriteAllText("") file2.WriteAllText("") file3.WriteAllText("") file4.WriteAllText("") file5.WriteAllText("") Dim parsedArgs = DefaultParse({"/recurse:" & dir.ToString() & "\*.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal({"{DIR}\a.vb", "{DIR}\b.vb", "{DIR}\d2\e.vb"}, parsedArgs.SourceFiles.Select(Function(file) file.Path.Replace(dir.ToString(), "{DIR}"))) parsedArgs = DefaultParse({"*.vb"}, dir.ToString()) parsedArgs.Errors.Verify() AssertEx.Equal({"{DIR}\a.vb", "{DIR}\b.vb"}, parsedArgs.SourceFiles.Select(Function(file) file.Path.Replace(dir.ToString(), "{DIR}"))) parsedArgs = DefaultParse({"/reCURSE:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("recurse", ":<wildcard>")) parsedArgs = DefaultParse({"/RECURSE: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("recurse", ":<wildcard>")) parsedArgs = DefaultParse({"/recurse", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("recurse", ":<wildcard>")) parsedArgs = DefaultParse({"/recurse+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/recurse+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/recurse-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/recurse-:")) ' TODO: Dev11 reports ERR_ArgumentRequired CleanupAllGeneratedFiles(file1.Path) CleanupAllGeneratedFiles(file2.Path) CleanupAllGeneratedFiles(file3.Path) CleanupAllGeneratedFiles(file4.Path) CleanupAllGeneratedFiles(file5.Path) End Sub <WorkItem(545991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545991")> <WorkItem(546009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546009")> <Fact> Public Sub Recurse_SimpleTests2() Dim folder = Temp.CreateDirectory() Dim file1 = folder.CreateFile("a.cs") Dim file2 = folder.CreateFile("b.vb") Dim file3 = folder.CreateFile("c.cpp") Dim file4 = folder.CreateDirectory("A").CreateFile("A_d.txt") Dim file5 = folder.CreateDirectory("B").CreateFile("B_e.vb") Dim file6 = folder.CreateDirectory("C").CreateFile("B_f.cs") file1.WriteAllText("") file2.WriteAllText("") file3.WriteAllText("") file4.WriteAllText("") file5.WriteAllText("") file6.WriteAllText("") Dim outWriter As New StringWriter() Dim exitCode As Integer = New MockVisualBasicCompiler(Nothing, folder.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/recurse:.", "b.vb", "/out:abc.dll"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2014: the value '.' is invalid for option 'recurse'", outWriter.ToString().Trim()) outWriter = New StringWriter() exitCode = New MockVisualBasicCompiler(Nothing, folder.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/recurse:. ", "b.vb", "/out:abc.dll"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2014: the value '.' is invalid for option 'recurse'", outWriter.ToString().Trim()) outWriter = New StringWriter() exitCode = New MockVisualBasicCompiler(Nothing, folder.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/recurse: . ", "/out:abc.dll"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2014: the value ' .' is invalid for option 'recurse'|vbc : error BC2008: no input sources specified", outWriter.ToString().Trim().Replace(vbCrLf, "|")) outWriter = New StringWriter() exitCode = New MockVisualBasicCompiler(Nothing, folder.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/recurse:./.", "/out:abc.dll"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2014: the value './.' is invalid for option 'recurse'|vbc : error BC2008: no input sources specified", outWriter.ToString().Trim().Replace(vbCrLf, "|")) Dim args As VisualBasicCommandLineArguments Dim resolvedSourceFiles As String() args = DefaultParse({"/recurse:*.cp*", "/recurse:b\*.v*", "/out:a.dll"}, folder.Path) args.Errors.Verify() resolvedSourceFiles = args.SourceFiles.Select(Function(f) f.Path).ToArray() AssertEx.Equal({folder.Path + "\c.cpp", folder.Path + "\b\B_e.vb"}, resolvedSourceFiles) args = DefaultParse({"/recurse:.\\\\\\*.vb", "/out:a.dll"}, folder.Path) args.Errors.Verify() resolvedSourceFiles = args.SourceFiles.Select(Function(f) f.Path).ToArray() Assert.Equal(2, resolvedSourceFiles.Length) args = DefaultParse({"/recurse:.////*.vb", "/out:a.dll"}, folder.Path) args.Errors.Verify() resolvedSourceFiles = args.SourceFiles.Select(Function(f) f.Path).ToArray() Assert.Equal(2, resolvedSourceFiles.Length) CleanupAllGeneratedFiles(file1.Path) CleanupAllGeneratedFiles(file2.Path) CleanupAllGeneratedFiles(file3.Path) CleanupAllGeneratedFiles(file4.Path) CleanupAllGeneratedFiles(file5.Path) CleanupAllGeneratedFiles(file6.Path) End Sub <WorkItem(948285, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948285")> <Fact> Public Sub Recurse_SimpleTests3() Dim folder = Temp.CreateDirectory() Dim outWriter = New StringWriter() Dim exitCode = New MockVisualBasicCompiler(Nothing, folder.Path, {"/nologo", "/preferreduilang:en", "/t:exe", "/out:abc.exe"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2008: no input sources specified", outWriter.ToString().Trim().Replace(vbCrLf, "|")) End Sub <Fact> Public Sub Reference_SimpleTests() Dim parsedArgs = DefaultParse({"/nostdlib", "/vbruntime-", "/r:a", "/REFERENCE:b,,,,c", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal({"a", "b", "c"}, parsedArgs.MetadataReferences. Where(Function(res) Not res.Properties.EmbedInteropTypes AndAlso Not res.Reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)). Select(Function(res) res.Reference)) parsedArgs = DefaultParse({"/Reference: ,,, b ,,", "/nostdlib", "/vbruntime-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal({" ", " b "}, parsedArgs.MetadataReferences. Where(Function(res) Not res.Properties.EmbedInteropTypes AndAlso Not res.Reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)). Select(Function(res) res.Reference)) parsedArgs = DefaultParse({"/r:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("r", ":<file_list>")) parsedArgs = DefaultParse({"/R", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("r", ":<file_list>")) parsedArgs = DefaultParse({"/reference+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/reference+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/reference-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/reference-:")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub Private Class SimpleMetadataResolver Inherits MetadataReferenceResolver Private ReadOnly _pathResolver As RelativePathResolver Public Sub New(baseDirectory As String) _pathResolver = New RelativePathResolver(ImmutableArray(Of String).Empty, baseDirectory) End Sub Public Overrides Function ResolveReference(reference As String, baseFilePath As String, properties As MetadataReferenceProperties) As ImmutableArray(Of PortableExecutableReference) Dim resolvedPath = _pathResolver.ResolvePath(reference, baseFilePath) If resolvedPath Is Nothing OrElse Not File.Exists(reference) Then Return Nothing End If Return ImmutableArray.Create(MetadataReference.CreateFromFile(resolvedPath, properties)) End Function Public Overrides Function Equals(other As Object) As Boolean Return True End Function Public Overrides Function GetHashCode() As Integer Return 1 End Function End Class <Fact> Public Sub Reference_CorLibraryAddedWhenThereAreUnresolvedReferences() Dim parsedArgs = DefaultParse({"/r:unresolved", "a.vb"}, _baseDirectory) Dim metadataResolver = New SimpleMetadataResolver(_baseDirectory) Dim references = parsedArgs.ResolveMetadataReferences(metadataResolver).ToImmutableArray() Assert.Equal(4, references.Length) Assert.Contains(references, Function(r) r.IsUnresolved) Assert.Contains(references, Function(r) Dim peRef = TryCast(r, PortableExecutableReference) Return peRef IsNot Nothing AndAlso peRef.FilePath.EndsWith("mscorlib.dll", StringComparison.Ordinal) End Function) End Sub <Fact> Public Sub Reference_CorLibraryAddedWhenThereAreNoUnresolvedReferences() Dim parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) Dim metadataResolver = New SimpleMetadataResolver(_baseDirectory) Dim references = parsedArgs.ResolveMetadataReferences(metadataResolver).ToImmutableArray() Assert.Equal(3, references.Length) Assert.DoesNotContain(references, Function(r) r.IsUnresolved) Assert.Contains(references, Function(r) Dim peRef = TryCast(r, PortableExecutableReference) Return peRef IsNot Nothing AndAlso peRef.FilePath.EndsWith("mscorlib.dll", StringComparison.Ordinal) End Function) End Sub <Fact> Public Sub ParseAnalyzers() Dim parsedArgs = DefaultParse({"/a:goo.dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(1, parsedArgs.AnalyzerReferences.Length) Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences(0).FilePath) parsedArgs = DefaultParse({"/analyzer:goo.dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(1, parsedArgs.AnalyzerReferences.Length) Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences(0).FilePath) parsedArgs = DefaultParse({"/analyzer:""goo.dll""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(1, parsedArgs.AnalyzerReferences.Length) Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences(0).FilePath) parsedArgs = DefaultParse({"/a:goo.dll,bar.dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(2, parsedArgs.AnalyzerReferences.Length) Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences(0).FilePath) Assert.Equal("bar.dll", parsedArgs.AnalyzerReferences(1).FilePath) parsedArgs = DefaultParse({"/a:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("a", ":<file_list>")) parsedArgs = DefaultParse({"/a", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("a", ":<file_list>")) End Sub <Fact> Public Sub Analyzers_Missing() Dim source = "Imports System" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/a:missing.dll", "a.vb"}) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2017: could not find library 'missing.dll'", outWriter.ToString().Trim()) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub Analyzers_Empty() Dim source = "Imports System" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/a:" + GetType(Object).Assembly.Location, "a.vb"}) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) Assert.DoesNotContain("warning", outWriter.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub Analyzers_Found() Dim source = "Imports System " + vbCrLf + "Public Class Tester" + vbCrLf + "End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' This assembly has a MockDiagnosticAnalyzer type which should get run by this compilation. Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb"}) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) ' Diagnostic cannot instantiate Assert.True(outWriter.ToString().Contains("warning BC42376")) ' Diagnostic is thrown Assert.True(outWriter.ToString().Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared")) Assert.True(outWriter.ToString().Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared")) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub Analyzers_WithRuleSet() Dim source = "Imports System " + vbCrLf + "Public Class Tester" + vbCrLf + "End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim rulesetSource = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed"> <Rule Id="Warning01" Action="Error"/> <Rule Id="Test02" Action="Warning"/> <Rule Id="Warning03" Action="None"/> </Rules> </RuleSet> Dim ruleSetFile = CreateRuleSetFile(rulesetSource) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb", "/ruleset:" + ruleSetFile.Path}) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) ' Diagnostic cannot instantiate Assert.True(outWriter.ToString().Contains("warning BC42376")) '' Diagnostic thrown as error 'Assert.True(outWriter.ToString().Contains("error Warning01")) ' Diagnostic is suppressed Assert.False(outWriter.ToString().Contains("warning Warning03")) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub Analyzers_CommandLineOverridesRuleset1() Dim source = "Imports System " + vbCrLf + "Public Class Tester" + vbCrLf + "End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim rulesetSource = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <IncludeAll Action="Warning"/> </RuleSet> Dim ruleSetFile = CreateRuleSetFile(rulesetSource) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/preferreduilang:en", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb", "/ruleset:" & ruleSetFile.Path, "/warnaserror", "/nowarn:42376" }) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) ' Diagnostics thrown as error: command line always overrides ruleset. Dim output = outWriter.ToString() Assert.Contains("error Warning01", output, StringComparison.Ordinal) Assert.Contains("error Warning03", output, StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) vbc = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb", "/warnaserror+", "/ruleset:" & ruleSetFile.Path, "/nowarn:42376" }) exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) ' Diagnostics thrown as error: command line always overrides ruleset. output = outWriter.ToString() Assert.Contains("error Warning01", output, StringComparison.Ordinal) Assert.Contains("error Warning03", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub Analyzer_CommandLineOverridesRuleset2() Dim source = "Imports System " + vbCrLf + "Public Class Tester" + vbCrLf + "End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim rulesetSource = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed"> <Rule Id="Warning01" Action="Error"/> <Rule Id="Warning03" Action="Warning"/> </Rules> </RuleSet> Dim ruleSetFile = CreateRuleSetFile(rulesetSource) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb", "/ruleset:" & ruleSetFile.Path, "/nowarn" }) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) ' Diagnostics suppressed: command line always overrides ruleset. Dim output = outWriter.ToString() Assert.DoesNotContain("Warning01", output, StringComparison.Ordinal) Assert.DoesNotContain("BC31072", output, StringComparison.Ordinal) Assert.DoesNotContain("Warning03", output, StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) vbc = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb", "/nowarn", "/ruleset:" & ruleSetFile.Path }) exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) ' Diagnostics suppressed: command line always overrides ruleset. output = outWriter.ToString() Assert.DoesNotContain("Warning01", output, StringComparison.Ordinal) Assert.DoesNotContain("BC31072", output, StringComparison.Ordinal) Assert.DoesNotContain("Warning03", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub Analyzers_WithRuleSetIncludeAll() Dim source = "Imports System \r\n Public Class Tester \r\n Public Sub Goo() \r\n Dim x As Integer \r\n End Sub \r\n End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim rulesetSource = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <IncludeAll Action="Error"/> <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed"> <Rule Id="Warning01" Action="Error"/> <Rule Id="Test02" Action="Warning"/> <Rule Id="Warning03" Action="None"/> </Rules> </RuleSet> Dim ruleSetFile = CreateRuleSetFile(rulesetSource) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb", "/ruleset:" + ruleSetFile.Path}) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) ' Compiler warnings as errors Assert.True(outWriter.ToString().Contains("error BC42376")) ' User diagnostics not thrown due to compiler errors Assert.False(outWriter.ToString().Contains("Warning01")) Assert.False(outWriter.ToString().Contains("Warning03")) CleanupAllGeneratedFiles(file.Path) End Sub Private Function CreateRuleSetFile(source As XDocument) As TempFile Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.ruleset") file.WriteAllText(source.ToString()) Return file End Function <Fact> Public Sub RulesetSwitchPositive() Dim source = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <IncludeAll Action="Warning"/> <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed"> <Rule Id="CA1012" Action="Error"/> <Rule Id="CA1013" Action="Warning"/> <Rule Id="CA1014" Action="None"/> </Rules> </RuleSet> Dim file = CreateRuleSetFile(source) Dim parsedArgs = DefaultParse(New String() {"/ruleset:" + file.Path, "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(expected:=file.Path, actual:=parsedArgs.RuleSetPath) Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1012")) Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions("CA1012") = ReportDiagnostic.Error) Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1013")) Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions("CA1013") = ReportDiagnostic.Warn) Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1014")) Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions("CA1014") = ReportDiagnostic.Suppress) Assert.True(parsedArgs.CompilationOptions.GeneralDiagnosticOption = ReportDiagnostic.Warn) End Sub <Fact> Public Sub RuleSetSwitchQuoted() Dim source = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <IncludeAll Action="Warning"/> <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed"> <Rule Id="CA1012" Action="Error"/> <Rule Id="CA1013" Action="Warning"/> <Rule Id="CA1014" Action="None"/> </Rules> </RuleSet> Dim file = CreateRuleSetFile(source) Dim parsedArgs = DefaultParse(New String() {"/ruleset:" + """" + file.Path + """", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(expected:=file.Path, actual:=parsedArgs.RuleSetPath) End Sub <Fact> Public Sub RulesetSwitchParseErrors() Dim parsedArgs = DefaultParse(New String() {"/ruleset", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("ruleset", ":<file>")) Assert.Null(parsedArgs.RuleSetPath) parsedArgs = DefaultParse(New String() {"/ruleset", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("ruleset", ":<file>")) Assert.Null(parsedArgs.RuleSetPath) parsedArgs = DefaultParse(New String() {"/ruleset:blah", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah"), "File not found.")) Assert.Equal(expected:=Path.Combine(TempRoot.Root, "blah"), actual:=parsedArgs.RuleSetPath) parsedArgs = DefaultParse(New String() {"/ruleset:blah;blah.ruleset", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah;blah.ruleset"), "File not found.")) Assert.Equal(expected:=Path.Combine(TempRoot.Root, "blah;blah.ruleset"), actual:=parsedArgs.RuleSetPath) Dim file = CreateRuleSetFile(New XDocument()) parsedArgs = DefaultParse(New String() {"/ruleset:" + file.Path, "a.cs"}, _baseDirectory) 'parsedArgs.Errors.Verify( ' Diagnostic(ERRID.ERR_CantReadRulesetFile).WithArguments(file.Path, "Root element is missing.")) Assert.Equal(expected:=file.Path, actual:=parsedArgs.RuleSetPath) Dim err = parsedArgs.Errors.Single() Assert.Equal(ERRID.ERR_CantReadRulesetFile, err.Code) Assert.Equal(2, err.Arguments.Count) Assert.Equal(file.Path, DirectCast(err.Arguments(0), String)) Dim currentUICultureName = Thread.CurrentThread.CurrentUICulture.Name If currentUICultureName.Length = 0 OrElse currentUICultureName.StartsWith("en", StringComparison.OrdinalIgnoreCase) Then Assert.Equal(err.Arguments(1), "Root element is missing.") End If End Sub <Fact> Public Sub Target_SimpleTests() Dim parsedArgs = DefaultParse({"/target:exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/t:module", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:library", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/TARGET:winexe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:winmdobj", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:appcontainerexe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:winexe", "/T:exe", "/target:module", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/t", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("t", ":exe|winexe|library|module|appcontainerexe|winmdobj")) parsedArgs = DefaultParse({"/target:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("target", ":exe|winexe|library|module|appcontainerexe|winmdobj")) parsedArgs = DefaultParse({"/target:xyz", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("target", "xyz")) parsedArgs = DefaultParse({"/T+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/T+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/TARGET-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/TARGET-:")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact> Public Sub Target_SimpleTestsNoSourceFile() Dim parsedArgs = DefaultParse({"/target:exe"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/t:module"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:library"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/TARGET:winexe"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:winmdobj"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:appcontainerexe"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:winexe", "/T:exe", "/target:module"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/t"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("t", ":exe|winexe|library|module|appcontainerexe|winmdobj"), Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) parsedArgs = DefaultParse({"/target:"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("target", ":exe|winexe|library|module|appcontainerexe|winmdobj"), Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) parsedArgs = DefaultParse({"/target:xyz"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("target", "xyz"), Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) parsedArgs = DefaultParse({"/T+"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/T+"), Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/TARGET-:"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/TARGET-:"), Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact> Public Sub Utf8Output() Dim parsedArgs = DefaultParse({"/utf8output", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.Utf8Output) parsedArgs = DefaultParse({"/utf8output+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.Utf8Output) parsedArgs = DefaultParse({"/utf8output-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.Utf8Output) ' default parsedArgs = DefaultParse({"/nologo", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.Utf8Output) ' overriding parsedArgs = DefaultParse({"/utf8output+", "/utf8output-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.Utf8Output) ' errors parsedArgs = DefaultParse({"/utf8output:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("utf8output")) End Sub <Fact> Public Sub Debug() Dim platformPdbKind = If(PathUtilities.IsUnixLikePlatform, DebugInformationFormat.PortablePdb, DebugInformationFormat.Pdb) Dim parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) Assert.False(parsedArgs.EmitPdb) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.False(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug+", "/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.False(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug:full", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug:FULL", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug:pdbonly", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug:portable", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, DebugInformationFormat.PortablePdb) parsedArgs = DefaultParse({"/debug:embedded", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, DebugInformationFormat.Embedded) parsedArgs = DefaultParse({"/debug:PDBONLY", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug:full", "/debug:pdbonly", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug:pdbonly", "/debug:full", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat) parsedArgs = DefaultParse({"/debug:pdbonly", "/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.False(parsedArgs.EmitPdb) Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat) parsedArgs = DefaultParse({"/debug:pdbonly", "/debug-", "/debug", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat) parsedArgs = DefaultParse({"/debug:pdbonly", "/debug-", "/debug+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat) parsedArgs = DefaultParse({"/debug:embedded", "/debug-", "/debug+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat) parsedArgs = DefaultParse({"/debug:embedded", "/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.False(parsedArgs.EmitPdb) Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat) parsedArgs = DefaultParse({"/debug:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("debug", "")) parsedArgs = DefaultParse({"/debug:+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("debug", "+")) parsedArgs = DefaultParse({"/debug:invalid", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("debug", "invalid")) parsedArgs = DefaultParse({"/debug-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("debug")) parsedArgs = DefaultParse({"/pdb:something", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/pdb:something")) End Sub <Fact> Public Sub SourceLink() Dim parsedArgs = DefaultParse({"/sourcelink:sl.json", "/debug:portable", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(_baseDirectory, "sl.json"), parsedArgs.SourceLink) parsedArgs = DefaultParse({"/sourcelink:sl.json", "/debug:embedded", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(_baseDirectory, "sl.json"), parsedArgs.SourceLink) parsedArgs = DefaultParse({"/sourcelink:""s l.json""", "/debug:embedded", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(_baseDirectory, "s l.json"), parsedArgs.SourceLink) parsedArgs = DefaultParse({"/sourcelink:sl.json", "/debug:full", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/sourcelink:sl.json", "/debug:pdbonly", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/sourcelink:sl.json", "/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SourceLinkRequiresPdb)) parsedArgs = DefaultParse({"/sourcelink:sl.json", "/debug+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/sourcelink:sl.json", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SourceLinkRequiresPdb)) End Sub <Fact> Public Sub SourceLink_EndToEnd_EmbeddedPortable() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText(" Class C Public Shared Sub Main() End Sub End Class") Dim sl = dir.CreateFile("sl.json") sl.WriteAllText("{ ""documents"" : {} }") Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/debug:embedded", "/sourcelink:sl.json", "a.vb"}) Dim exitCode As Integer = vbc.Run(outWriter) Assert.Equal(0, exitCode) Dim peStream = File.OpenRead(Path.Combine(dir.Path, "a.exe")) Using peReader = New PEReader(peStream) Dim entry = peReader.ReadDebugDirectory().Single(Function(e) e.Type = DebugDirectoryEntryType.EmbeddedPortablePdb) Using mdProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry) Dim blob = mdProvider.GetMetadataReader().GetSourceLinkBlob() AssertEx.Equal(File.ReadAllBytes(sl.Path), blob) End Using End Using CleanupAllGeneratedFiles(src.Path) End Sub <Fact> Public Sub SourceLink_EndToEnd_Portable() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText(" Class C Public Shared Sub Main() End Sub End Class") Dim sl = dir.CreateFile("sl.json") sl.WriteAllText("{ ""documents"" : {} }") Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/debug:portable", "/sourcelink:sl.json", "a.vb"}) Dim exitCode As Integer = vbc.Run(outWriter) Assert.Equal(0, exitCode) Dim pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")) Using mdProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream) Dim blob = mdProvider.GetMetadataReader().GetSourceLinkBlob() AssertEx.Equal(File.ReadAllBytes(sl.Path), blob) End Using CleanupAllGeneratedFiles(src.Path) End Sub <Fact> Public Sub Embed() Dim parsedArgs = DefaultParse({"a.vb "}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Empty(parsedArgs.EmbeddedFiles) parsedArgs = DefaultParse({"/embed", "/debug:portable", "a.vb", "b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal(parsedArgs.SourceFiles, parsedArgs.EmbeddedFiles) AssertEx.Equal( {"a.vb", "b.vb", "c.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:a.vb", "/embed:b.vb", "/debug:embedded", "a.vb", "b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a.vb", "b.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:a.vb;b.vb", "/debug:portable", "a.vb", "b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a.vb", "b.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:a.vb,b.vb", "/debug:portable", "a.vb", "b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a.vb", "b.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:""a,b.vb""", "/debug:portable", "a,b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a,b.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:\""a,b.vb\""", "/debug:portable", "a,b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a,b.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:\""""a.vb,b.vb""\""", "/debug:portable", "a.vb", "b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a.vb", "b.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:a.txt", "/embed", "/debug:portable", "a.vb", "b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a.txt", "a.vb", "b.vb", "c.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_CannotEmbedWithoutPdb)) parsedArgs = DefaultParse({"/embed:a.txt", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_CannotEmbedWithoutPdb)) parsedArgs = DefaultParse({"/embed", "/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_CannotEmbedWithoutPdb)) parsedArgs = DefaultParse({"/embed:a.txt", "/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_CannotEmbedWithoutPdb)) parsedArgs = DefaultParse({"/embed", "/debug:full", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/embed", "/debug:pdbonly", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/embed", "/debug+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() End Sub <Theory> <InlineData("/debug:portable", "/embed", {"embed.vb", "embed2.vb", "embed.xyz"})> <InlineData("/debug:portable", "/embed:embed.vb", {"embed.vb", "embed.xyz"})> <InlineData("/debug:portable", "/embed:embed2.vb", {"embed2.vb"})> <InlineData("/debug:portable", "/embed:embed.xyz", {"embed.xyz"})> <InlineData("/debug:embedded", "/embed", {"embed.vb", "embed2.vb", "embed.xyz"})> <InlineData("/debug:embedded", "/embed:embed.vb", {"embed.vb", "embed.xyz"})> <InlineData("/debug:embedded", "/embed:embed2.vb", {"embed2.vb"})> <InlineData("/debug:embedded", "/embed:embed.xyz", {"embed.xyz"})> <InlineData("/debug:full", "/embed", {"embed.vb", "embed2.vb", "embed.xyz"})> <InlineData("/debug:full", "/embed:embed.vb", {"embed.vb", "embed.xyz"})> <InlineData("/debug:full", "/embed:embed2.vb", {"embed2.vb"})> <InlineData("/debug:full", "/embed:embed.xyz", {"embed.xyz"})> Public Sub Embed_EndToEnd(debugSwitch As String, embedSwitch As String, expectedEmbedded As String()) ' embed.vb: large enough To compress, has #line directives Const embed_vb = "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Class Program Shared Sub Main() #ExternalSource(""embed.xyz"", 1) System.Console.WriteLine(""Hello, World"") System.Console.WriteLine(""Goodbye, World"") #End ExternalSource End Sub End Class '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''" ' embed2.vb: small enough to not compress, no sequence points Const embed2_vb = "Class C End Class" ' target of #ExternalSource Const embed_xyz = "print Hello, World print Goodbye, World" Assert.True(embed_vb.Length >= EmbeddedText.CompressionThreshold) Assert.True(embed2_vb.Length < EmbeddedText.CompressionThreshold) Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("embed.vb") Dim src2 = dir.CreateFile("embed2.vb") Dim txt = dir.CreateFile("embed.xyz") src.WriteAllText(embed_vb) src2.WriteAllText(embed2_vb) txt.WriteAllText(embed_xyz) Dim expectedEmbeddedMap = New Dictionary(Of String, String)() If expectedEmbedded.Contains("embed.vb") Then expectedEmbeddedMap.Add(src.Path, embed_vb) End If If expectedEmbedded.Contains("embed2.vb") Then expectedEmbeddedMap.Add(src2.Path, embed2_vb) End If If expectedEmbedded.Contains("embed.xyz") Then expectedEmbeddedMap.Add(txt.Path, embed_xyz) End If Dim output = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", debugSwitch, embedSwitch, "embed.vb", "embed2.vb"}) Dim exitCode = vbc.Run(output) Assert.Equal("", output.ToString().Trim()) Assert.Equal(0, exitCode) Select Case debugSwitch Case "/debug:embedded" ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb:=True) Case "/debug:portable" ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb:=False) Case "/debug:full" ValidateEmbeddedSources_Windows(expectedEmbeddedMap, dir) End Select Assert.Empty(expectedEmbeddedMap) CleanupAllGeneratedFiles(src.Path) End Sub Private Shared Sub ValidateEmbeddedSources_Portable(expectedEmbeddedMap As Dictionary(Of String, String), dir As TempDirectory, isEmbeddedPdb As Boolean) Using peReader As New PEReader(File.OpenRead(Path.Combine(dir.Path, "embed.exe"))) Dim entry = peReader.ReadDebugDirectory().SingleOrDefault(Function(e) e.Type = DebugDirectoryEntryType.EmbeddedPortablePdb) Assert.Equal(isEmbeddedPdb, entry.DataSize > 0) Using mdProvider As MetadataReaderProvider = If( isEmbeddedPdb, peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry), MetadataReaderProvider.FromPortablePdbStream(File.OpenRead(Path.Combine(dir.Path, "embed.pdb")))) Dim mdReader = mdProvider.GetMetadataReader() For Each handle In mdReader.Documents Dim doc = mdReader.GetDocument(handle) Dim docPath = mdReader.GetString(doc.Name) Dim embeddedSource = mdReader.GetEmbeddedSource(handle) If embeddedSource Is Nothing Then Continue For End If Assert.True(TypeOf embeddedSource.Encoding Is UTF8Encoding AndAlso embeddedSource.Encoding.GetPreamble().Length = 0) Assert.Equal(expectedEmbeddedMap(docPath), embeddedSource.ToString()) Assert.True(expectedEmbeddedMap.Remove(docPath)) Next End Using End Using End Sub Private Shared Sub ValidateEmbeddedSources_Windows(expectedEmbeddedMap As Dictionary(Of String, String), dir As TempDirectory) Dim symReader As ISymUnmanagedReader5 = Nothing Try symReader = SymReaderFactory.CreateReader(File.OpenRead(Path.Combine(dir.Path, "embed.pdb"))) For Each doc In symReader.GetDocuments() Dim docPath = doc.GetName() Dim sourceBlob = doc.GetEmbeddedSource() If sourceBlob.Array Is Nothing Then Continue For End If Dim sourceStr = Encoding.UTF8.GetString(sourceBlob.Array, sourceBlob.Offset, sourceBlob.Count) Assert.Equal(expectedEmbeddedMap(docPath), sourceStr) Assert.True(expectedEmbeddedMap.Remove(docPath)) Next Finally symReader?.Dispose() End Try End Sub <CompilerTrait(CompilerFeature.Determinism)> <Fact> Public Sub PathMapParser() Dim s = PathUtilities.DirectorySeparatorStr Dim parsedArgs = DefaultParse({"/pathmap:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/pathmap:").WithLocation(1, 1) ) Assert.Equal(ImmutableArray.Create(Of KeyValuePair(Of String, String))(), parsedArgs.PathMap) parsedArgs = DefaultParse({"/pathmap:K1=V1", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("K1" & s, "V1" & s), parsedArgs.PathMap(0)) parsedArgs = DefaultParse({$"/pathmap:abc{s}=/", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("abc" & s, "/"), parsedArgs.PathMap(0)) parsedArgs = DefaultParse({"/pathmap:K1=V1,K2=V2", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("K1" & s, "V1" & s), parsedArgs.PathMap(0)) Assert.Equal(KeyValuePairUtil.Create("K2" & s, "V2" & s), parsedArgs.PathMap(1)) parsedArgs = DefaultParse({"/pathmap:,", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(ImmutableArray.Create(Of KeyValuePair(Of String, String))(), parsedArgs.PathMap) parsedArgs = DefaultParse({"/pathmap:,,", "a.vb"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Count()) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(0).Code) parsedArgs = DefaultParse({"/pathmap:,,,", "a.vb"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Count()) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(0).Code) parsedArgs = DefaultParse({"/pathmap:k=,=v", "a.vb"}, _baseDirectory) Assert.Equal(2, parsedArgs.Errors.Count()) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(0).Code) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(1).Code) parsedArgs = DefaultParse({"/pathmap:k=v=bad", "a.vb"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Count()) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(0).Code) parsedArgs = DefaultParse({"/pathmap:k=", "a.vb"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Count()) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(0).Code) parsedArgs = DefaultParse({"/pathmap:=v", "a.vb"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Count()) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(0).Code) parsedArgs = DefaultParse({"/pathmap:""supporting spaces=is hard""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("supporting spaces" & s, "is hard" & s), parsedArgs.PathMap(0)) parsedArgs = DefaultParse({"/pathmap:""K 1=V 1"",""K 2=V 2""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("K 1" & s, "V 1" & s), parsedArgs.PathMap(0)) Assert.Equal(KeyValuePairUtil.Create("K 2" & s, "V 2" & s), parsedArgs.PathMap(1)) parsedArgs = DefaultParse({"/pathmap:""K 1""=""V 1"",""K 2""=""V 2""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("K 1" & s, "V 1" & s), parsedArgs.PathMap(0)) Assert.Equal(KeyValuePairUtil.Create("K 2" & s, "V 2" & s), parsedArgs.PathMap(1)) parsedArgs = DefaultParse({"/pathmap:""a ==,,b""=""1,,== 2"",""x ==,,y""=""3 4"",", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("a =,b" & s, "1,= 2" & s), parsedArgs.PathMap(0)) Assert.Equal(KeyValuePairUtil.Create("x =,y" & s, "3 4" & s), parsedArgs.PathMap(1)) parsedArgs = DefaultParse({"/pathmap:C:\temp\=/_1/,C:\temp\a\=/_2/,C:\temp\a\b\=/_3/", "a.cs", "a\b.cs", "a\b\c.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("C:\temp\a\b\", "/_3/"), parsedArgs.PathMap(0)) Assert.Equal(KeyValuePairUtil.Create("C:\temp\a\", "/_2/"), parsedArgs.PathMap(1)) Assert.Equal(KeyValuePairUtil.Create("C:\temp\", "/_1/"), parsedArgs.PathMap(2)) End Sub ' PathMapKeepsCrossPlatformRoot and PathMapInconsistentSlashes should be in an ' assembly that is ran cross-platform, but as no visual basic test assemblies are ' run cross-platform, put this here in the hopes that this will eventually be ported. <Theory> <InlineData("C:\", "/", "C:\", "/")> <InlineData("C:\temp\", "/temp/", "C:\temp", "/temp")> <InlineData("C:\temp\", "/temp/", "C:\temp\", "/temp/")> <InlineData("/", "C:\", "/", "C:\")> <InlineData("/temp/", "C:\temp\", "/temp", "C:\temp")> <InlineData("/temp/", "C:\temp\", "/temp/", "C:\temp\")> Public Sub PathMapKeepsCrossPlatformRoot(expectedFrom As String, expectedTo As String, sourceFrom As String, sourceTo As String) Dim pathmapArg = $"/pathmap:{sourceFrom}={sourceTo}" Dim parsedArgs = VisualBasicCommandLineParser.Default.Parse({pathmapArg, "a.vb"}, TempRoot.Root, RuntimeEnvironment.GetRuntimeDirectory(), Nothing) parsedArgs.Errors.Verify() Dim expected = New KeyValuePair(Of String, String)(expectedFrom, expectedTo) Assert.Equal(expected, parsedArgs.PathMap(0)) End Sub <Fact> Public Sub PathMapInconsistentSlashes() Dim Parse = Function(args() As String) As VisualBasicCommandLineArguments Dim parsedArgs = VisualBasicCommandLineParser.Default.Parse(args, TempRoot.Root, RuntimeEnvironment.GetRuntimeDirectory(), Nothing) parsedArgs.Errors.Verify() Return parsedArgs End Function Dim sep = PathUtilities.DirectorySeparatorChar Assert.Equal(New KeyValuePair(Of String, String)("C:\temp/goo" + sep, "/temp\goo" + sep), Parse({"/pathmap:C:\temp/goo=/temp\goo", "a.vb"}).PathMap(0)) Assert.Equal(New KeyValuePair(Of String, String)("noslash" + sep, "withoutslash" + sep), Parse({"/pathmap:noslash=withoutslash", "a.vb"}).PathMap(0)) Dim doublemap = Parse({"/pathmap:/temp=/goo,/temp/=/bar", "a.vb"}).PathMap Assert.Equal(New KeyValuePair(Of String, String)("/temp/", "/goo/"), doublemap(0)) Assert.Equal(New KeyValuePair(Of String, String)("/temp/", "/bar/"), doublemap(1)) End Sub <Fact> Public Sub NothingBaseDirectoryNotAddedToKeyFileSearchPaths() Dim args As VisualBasicCommandLineArguments = VisualBasicCommandLineParser.Default.Parse(New String() {}, Nothing, RuntimeEnvironment.GetRuntimeDirectory()) AssertEx.Equal(ImmutableArray.Create(Of String)(), args.KeyFileSearchPaths) End Sub <Fact> <WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")> Public Sub SdkPathArg() Dim parentDir = Temp.CreateDirectory() Dim sdkDir = parentDir.CreateDirectory("sdk") Dim sdkPath = sdkDir.Path Dim parser = VisualBasicCommandLineParser.Default.Parse({$"-sdkPath:{sdkPath}"}, parentDir.Path, Nothing) AssertEx.Equal(ImmutableArray.Create(sdkPath), parser.ReferencePaths) End Sub <Fact> <WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")> Public Sub SdkPathNoArg() Dim parentDir = Temp.CreateDirectory() Dim parser = VisualBasicCommandLineParser.Default.Parse({"file.vb", "-sdkPath", $"-out:{parentDir.Path}"}, parentDir.Path, Nothing) parser.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired, arguments:={"sdkpath", ":<path>"}).WithLocation(1, 1), Diagnostic(ERRID.WRN_CannotFindStandardLibrary1).WithArguments("System.dll").WithLocation(1, 1), Diagnostic(ERRID.ERR_LibNotFound).WithArguments("Microsoft.VisualBasic.dll").WithLocation(1, 1)) End Sub <Fact> <WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")> Public Sub SdkPathFollowedByNoSdkPath() Dim parentDir = Temp.CreateDirectory() Dim parser = VisualBasicCommandLineParser.Default.Parse({"file.vb", $"-out:{parentDir.Path}", "-sdkPath:path/to/sdk", "/noSdkPath"}, parentDir.Path, Nothing) AssertEx.Equal(ImmutableArray(Of String).Empty, parser.ReferencePaths) End Sub <Fact> <WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")> Public Sub NoSdkPathFollowedBySdkPath() Dim parentDir = Temp.CreateDirectory() Dim sdkDir = parentDir.CreateDirectory("sdk") Dim parser = VisualBasicCommandLineParser.Default.Parse({"file.vb", $"-out:{parentDir.Path}", "/noSdkPath", $"-sdkPath:{sdkDir.Path}"}, parentDir.Path, Nothing) AssertEx.Equal(ImmutableArray.Create(sdkDir.Path), parser.ReferencePaths) End Sub <Fact> <WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")> Public Sub NoSdkPathReferenceSystemDll() Dim source = " Module M End Module " Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/preferreduilang:en", "/nosdkpath", "/t:library", "a.vb"}) Dim exitCode = vbc.Run(outWriter, Nothing) Dim output = outWriter.ToString().Trim() Assert.Equal(1, exitCode) Assert.Contains("vbc : error BC2017: could not find library 'Microsoft.VisualBasic.dll'", output) CleanupAllGeneratedFiles(file.Path) End Sub <CompilerTrait(CompilerFeature.Determinism)> <Fact> Public Sub PathMapPdbDeterminism() Dim assertPdbEmit = Sub(dir As TempDirectory, pePdbPath As String, extraArgs As String()) Dim source = <compilation> Imports System Module Program Sub Main() End Sub End Module </compilation> Dim src = dir.CreateFile("a.vb").WriteAllText(source.Value) Dim pdbPath = Path.Combine(dir.Path, "a.pdb") Dim defaultArgs = {"/nologo", "/debug", "a.vb"} Dim isDeterministic = extraArgs.Contains("/deterministic") Dim args = defaultArgs.Concat(extraArgs).ToArray() Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(dir.Path, args) Dim exitCode = vbc.Run(outWriter) Assert.Equal(0, exitCode) Dim exePath = Path.Combine(dir.Path, "a.exe") Assert.True(File.Exists(exePath)) Assert.True(File.Exists(pdbPath)) Using peStream = File.OpenRead(exePath) PdbValidation.ValidateDebugDirectory(peStream, Nothing, pePdbPath, hashAlgorithm:=Nothing, hasEmbeddedPdb:=False, isDeterministic) End Using End Sub ' No mappings Using dir As New DisposableDirectory(Temp) Dim pePdbPath = Path.Combine(dir.Path, "a.pdb") assertPdbEmit(dir, pePdbPath, {}) End Using ' Simple mapping Using dir As New DisposableDirectory(Temp) Dim pePdbPath = "q:\a.pdb" assertPdbEmit(dir, pePdbPath, {$"/pathmap:{dir.Path}=q:\"}) End Using ' Simple mapping deterministic Using dir As New DisposableDirectory(Temp) Dim pePdbPath = "q:\a.pdb" assertPdbEmit(dir, pePdbPath, {$"/pathmap:{dir.Path}=q:\", "/deterministic"}) End Using ' Partial mapping Using dir As New DisposableDirectory(Temp) Dim subDir = dir.CreateDirectory("example") Dim pePdbPath = "q:\example\a.pdb" assertPdbEmit(subDir, pePdbPath, {$"/pathmap:{dir.Path}=q:\"}) End Using ' Legacy feature flag Using dir As New DisposableDirectory(Temp) Dim pePdbPath = Path.Combine(dir.Path, "a.pdb") assertPdbEmit(dir, "a.pdb", {"/features:pdb-path-determinism"}) End Using ' Unix path map Using dir As New DisposableDirectory(Temp) Dim pdbPath = Path.Combine(dir.Path, "a.pdb") assertPdbEmit(dir, "/a.pdb", {$"/pathmap:{dir.Path}=/"}) End Using ' Multi-specified path map with mixed slashes Using dir As New DisposableDirectory(Temp) Dim pdbPath = Path.Combine(dir.Path, "a.pdb") assertPdbEmit(dir, "/goo/a.pdb", {$"/pathmap:{dir.Path}=/goo,{dir.Path}{PathUtilities.DirectorySeparatorChar}=/bar"}) End Using End Sub <WorkItem(540891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540891")> <Fact> Public Sub ParseOut() Const baseDirectory As String = "C:\abc\def\baz" ' Should preserve fully qualified paths Dim parsedArgs = DefaultParse({"/out:C:\MyFolder\MyBinary.dll", "/t:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("MyBinary", parsedArgs.CompilationName) Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName) Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName) Assert.Equal("C:\MyFolder", parsedArgs.OutputDirectory) parsedArgs = DefaultParse({"/out:""C:\My Folder\MyBinary.dll""", "/t:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("MyBinary", parsedArgs.CompilationName) Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName) Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName) Assert.Equal("C:\My Folder", parsedArgs.OutputDirectory) parsedArgs = DefaultParse({"/refout:", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("refout", ":<file>").WithLocation(1, 1)) parsedArgs = DefaultParse({"/refout:ref.dll", "/refonly", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1)) parsedArgs = DefaultParse({"/refonly:incorrect", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("refonly").WithLocation(1, 1)) parsedArgs = DefaultParse({"/refout:ref.dll", "/target:module", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1)) parsedArgs = DefaultParse({"/refout:ref.dll", "/link:b", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/refonly", "/link:b", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/refonly", "/target:module", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1)) parsedArgs = DefaultParse({"/out:C:\""My Folder""\MyBinary.dll", "/t:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("C:""My Folder\MyBinary.dll").WithLocation(1, 1)) parsedArgs = DefaultParse({"/out:MyBinary.dll", "/t:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("MyBinary", parsedArgs.CompilationName) Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName) Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) parsedArgs = DefaultParse({"/out:Ignored.dll", "/out:MyBinary.dll", "/t:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("MyBinary", parsedArgs.CompilationName) Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName) Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) parsedArgs = DefaultParse({"/out:..\MyBinary.dll", "/t:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("MyBinary", parsedArgs.CompilationName) Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName) Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName) Assert.Equal("C:\abc\def", parsedArgs.OutputDirectory) ' not specified: exe parsedArgs = DefaultParse({"a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.exe", parsedArgs.OutputFileName) Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) ' not specified: dll parsedArgs = DefaultParse({"/target:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.dll", parsedArgs.OutputFileName) Assert.Equal("a.dll", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) ' not specified: module parsedArgs = DefaultParse({"/target:module", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Null(parsedArgs.CompilationName) Assert.Equal("a.netmodule", parsedArgs.OutputFileName) Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) ' not specified: appcontainerexe parsedArgs = DefaultParse({"/target:appcontainerexe", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.exe", parsedArgs.OutputFileName) Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) ' not specified: winmdobj parsedArgs = DefaultParse({"/target:winmdobj", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.winmdobj", parsedArgs.OutputFileName) Assert.Equal("a.winmdobj", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) ' drive-relative path: Dim currentDrive As Char = Directory.GetCurrentDirectory()(0) parsedArgs = DefaultParse({currentDrive + ":a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.vb")) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) ' UNC parsedArgs = DefaultParse({"/out:\\b", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("\\b")) Assert.Equal("a.exe", parsedArgs.OutputFileName) Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/out:\\server\share\file.exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("\\server\share", parsedArgs.OutputDirectory) Assert.Equal("file.exe", parsedArgs.OutputFileName) Assert.Equal("file", parsedArgs.CompilationName) Assert.Equal("file.exe", parsedArgs.CompilationOptions.ModuleName) ' invalid name parsedArgs = DefaultParse({"/out:a.b" & vbNullChar & "b", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("a.b" & vbNullChar & "b")) Assert.Equal("a.exe", parsedArgs.OutputFileName) Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) ' Temp Skip: Unicode? ' parsedArgs = DefaultParse({"/out:a" & ChrW(&HD800) & "b.dll", "a.vb"}, _baseDirectory) ' parsedArgs.Errors.Verify( ' Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("a" & ChrW(&HD800) & "b.dll")) ' Assert.Equal("a.exe", parsedArgs.OutputFileName) ' Assert.Equal("a", parsedArgs.CompilationName) ' Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) ' Temp Skip: error message changed (path) 'parsedArgs = DefaultParse({"/out:"" a.dll""", "a.vb"}, _baseDirectory) 'parsedArgs.Errors.Verify( ' Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(" a.dll")) 'Assert.Equal("a.exe", parsedArgs.OutputFileName) 'Assert.Equal("a", parsedArgs.CompilationName) 'Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) ' Dev11 reports BC2012: can't open 'a<>.z' for writing parsedArgs = DefaultParse({"/out:""a<>.dll""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("a<>.dll")) Assert.Equal("a.exe", parsedArgs.OutputFileName) Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) ' bad value parsedArgs = DefaultParse({"/out", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("out", ":<file>")) parsedArgs = DefaultParse({"/OUT:", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("out", ":<file>")) parsedArgs = DefaultParse({"/REFOUT:", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("refout", ":<file>")) parsedArgs = DefaultParse({"/refout:ref.dll", "/refonly", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1)) parsedArgs = DefaultParse({"/out+", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/out+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/out-:", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/out-:")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/out:.exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".exe")) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/t:exe", "/out:.exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".exe")) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/t:library", "/out:.dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".dll")) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/t:module", "/out:.netmodule", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(".netmodule", parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({".vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".exe")) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/t:exe", ".vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".exe")) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/t:library", ".vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".dll")) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/t:module", ".vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(".netmodule", parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName) End Sub <Fact> Public Sub ParseOut2() ' exe Dim parsedArgs = DefaultParse({"/out:.x", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(".x", parsedArgs.CompilationName) Assert.Equal(".x.exe", parsedArgs.OutputFileName) Assert.Equal(".x.exe", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:winexe", "/out:.x.eXe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(".x", parsedArgs.CompilationName) Assert.Equal(".x.eXe", parsedArgs.OutputFileName) Assert.Equal(".x.eXe", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:winexe", "/out:.exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".exe")) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) ' dll parsedArgs = DefaultParse({"/target:library", "/out:.x", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(".x", parsedArgs.CompilationName) Assert.Equal(".x.dll", parsedArgs.OutputFileName) Assert.Equal(".x.dll", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:library", "/out:.X.Dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(".X", parsedArgs.CompilationName) Assert.Equal(".X.Dll", parsedArgs.OutputFileName) Assert.Equal(".X.Dll", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:library", "/out:.dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".dll")) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) ' module parsedArgs = DefaultParse({"/target:module", "/out:.x", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Null(parsedArgs.CompilationName) Assert.Equal(".x", parsedArgs.OutputFileName) Assert.Equal(".x", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:module", "/out:x.dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Null(parsedArgs.CompilationName) Assert.Equal("x.dll", parsedArgs.OutputFileName) Assert.Equal("x.dll", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:module", "/out:.x.netmodule", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Null(parsedArgs.CompilationName) Assert.Equal(".x.netmodule", parsedArgs.OutputFileName) Assert.Equal(".x.netmodule", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:module", "/out:x", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Null(parsedArgs.CompilationName) Assert.Equal("x.netmodule", parsedArgs.OutputFileName) Assert.Equal("x.netmodule", parsedArgs.CompilationOptions.ModuleName) End Sub <Fact, WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> Public Sub ConsistentErrorMessageWhenProvidingNoKeyFile() Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/keyfile:", "/target:library", "/nologo", "/preferreduilang:en", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'keyfile' requires ':<file>'", outWriter.ToString().Trim()) End Sub <Fact, WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> Public Sub ConsistentErrorMessageWhenProvidingEmptyKeyFile() Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/keyfile:""""", "/target:library", "/nologo", "/preferreduilang:en", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'keyfile' requires ':<file>'", outWriter.ToString().Trim()) End Sub <Fact, WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> Public Sub ConsistentErrorMessageWhenProvidingNoKeyFile_PublicSign() Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/keyfile:", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'keyfile' requires ':<file>'", outWriter.ToString().Trim()) End Sub <Fact, WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> Public Sub ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign() Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/keyfile:""""", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'keyfile' requires ':<file>'", outWriter.ToString().Trim()) End Sub <Fact, WorkItem(531020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531020")> Public Sub ParseDocBreak1() Const baseDirectory As String = "C:\abc\def\baz" ' In dev11, this appears to be equivalent to /doc- (i.e. don't parse and don't output). Dim parsedArgs = DefaultParse({"/doc:""""", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("doc", ":<file>")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) End Sub <Fact, WorkItem(705173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705173")> Public Sub Ensure_UTF8_Explicit_Prefix_In_Documentation_Comment_File() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /doc:{1}\src.xml /t:library {0}", src.ToString(), dir.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Dim fileContents = File.ReadAllBytes(dir.ToString() & "\src.xml") Assert.InRange(fileContents.Length, 4, Integer.MaxValue) Assert.Equal(&HEF, fileContents(0)) Assert.Equal(&HBB, fileContents(1)) Assert.Equal(&HBF, fileContents(2)) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(733242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/733242")> Public Sub Bug733242() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim xml = dir.CreateFile("a.xml") xml.WriteAllText("EMPTY") Using xmlFileHandle As FileStream = File.Open(xml.ToString(), FileMode.Open, FileAccess.Read, FileShare.Delete Or FileShare.ReadWrite) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc+ {0}", src.ToString()), startFolder:=dir.ToString(), expectedRetCode:=0) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))) Using reader As New StreamReader(xmlFileHandle) Dim content = reader.ReadToEnd() AssertOutput( <text> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> a </name> </assembly> <members> <member name="T:C"> <summary>ABC...XYZ</summary> </member> </members> </doc> ]]> </text>, content) End Using End Using CleanupAllGeneratedFiles(src.Path) CleanupAllGeneratedFiles(xml.Path) End Sub <Fact, WorkItem(768605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768605")> Public Sub Bug768605() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC&lt;/summary&gt; Class C: End Class ''' &lt;summary&gt;XYZ&lt;/summary&gt; Class E: End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim xml = dir.CreateFile("a.xml") xml.WriteAllText("EMPTY") Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc+ {0}", src.ToString()), startFolder:=dir.ToString(), expectedRetCode:=0) AssertOutput(<text></text>, output) Using reader As New StreamReader(xml.ToString()) Dim content = reader.ReadToEnd() AssertOutput( <text> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> a </name> </assembly> <members> <member name="T:C"> <summary>ABC</summary> </member> <member name="T:E"> <summary>XYZ</summary> </member> </members> </doc> ]]> </text>, content) End Using src.WriteAllText( <text> ''' &lt;summary&gt;ABC&lt;/summary&gt; Class C: End Class </text>.Value.Replace(vbLf, vbCrLf)) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc+ {0}", src.ToString()), startFolder:=dir.ToString(), expectedRetCode:=0) AssertOutput(<text></text>, output) Using reader As New StreamReader(xml.ToString()) Dim content = reader.ReadToEnd() AssertOutput( <text> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> a </name> </assembly> <members> <member name="T:C"> <summary>ABC</summary> </member> </members> </doc> ]]> </text>, content) End Using CleanupAllGeneratedFiles(src.Path) CleanupAllGeneratedFiles(xml.Path) End Sub <Fact, WorkItem(705148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705148")> Public Sub Bug705148a() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc:abcdfg.xyz /doc+ {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(705148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705148")> Public Sub Bug705148b() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc /out:MyXml.dll {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "MyXml.xml"))) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(705148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705148")> Public Sub Bug705148c() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc:doc.xml /doc+ {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(705202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705202")> Public Sub Bug705202a() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc:doc.xml /out:out.dll {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml"))) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(705202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705202")> Public Sub Bug705202b() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc:doc.xml /doc /out:out.dll {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "out.xml"))) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(705202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705202")> Public Sub Bug705202c() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc:doc.xml /out:out.dll /doc+ {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "out.xml"))) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(531021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531021")> Public Sub ParseDocBreak2() ' In dev11, if you give an invalid file name, the documentation comments ' are parsed but writing the XML file fails with (warning!) BC42311. Const baseDirectory As String = "C:\abc\def\baz" Dim parsedArgs = DefaultParse({"/doc:"" """, "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments(" ", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) parsedArgs = DefaultParse({"/doc:"" \ """, "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments(" \ ", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' UNC parsedArgs = DefaultParse({"/doc:\\b", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments("\\b", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Even though the format was incorrect ' invalid name: parsedArgs = DefaultParse({"/doc:a.b" + ChrW(0) + "b", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments("a.b" + ChrW(0) + "b", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Even though the format was incorrect parsedArgs = DefaultParse({"/doc:a" + ChrW(55296) + "b.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments("a" + ChrW(55296) + "b.xml", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Even though the format was incorrect parsedArgs = DefaultParse({"/doc:""a<>.xml""", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments("a<>.xml", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Even though the format was incorrect End Sub <Fact> Public Sub ParseDoc() Const baseDirectory As String = "C:\abc\def\baz" Dim parsedArgs = DefaultParse({"/doc:", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("doc", ":<file>")) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) parsedArgs = DefaultParse({"/doc", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) parsedArgs = DefaultParse({"/doc+", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) parsedArgs = DefaultParse({"/doc-", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.None, parsedArgs.ParseOptions.DocumentationMode) parsedArgs = DefaultParse({"/doc+:abc.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("doc")) Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) parsedArgs = DefaultParse({"/doc-:a.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("doc")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.None, parsedArgs.ParseOptions.DocumentationMode) ' Should preserve fully qualified paths parsedArgs = DefaultParse({"/doc:C:\MyFolder\MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\MyFolder\MyBinary.xml", parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Should handle quotes parsedArgs = DefaultParse({"/doc:""C:\My Folder\MyBinary.xml""", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\My Folder\MyBinary.xml", parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Should expand partially qualified paths parsedArgs = DefaultParse({"/doc:MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Should expand partially qualified paths parsedArgs = DefaultParse({"/doc:..\MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\abc\def\MyBinary.xml", parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' drive-relative path: Dim currentDrive As Char = Directory.GetCurrentDirectory()(0) parsedArgs = DefaultParse({"/doc:" + currentDrive + ":a.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments(currentDrive + ":a.xml", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Even though the format was incorrect ' UNC parsedArgs = DefaultParse({"/doc:\\server\share\file.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("\\server\share\file.xml", parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) End Sub <Fact> Public Sub ParseDocAndOut() Const baseDirectory As String = "C:\abc\def\baz" ' Can specify separate directories for binary and XML output. Dim parsedArgs = DefaultParse({"/doc:a\b.xml", "/out:c\d.exe", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\abc\def\baz\a\b.xml", parsedArgs.DocumentationPath) Assert.Equal("C:\abc\def\baz\c", parsedArgs.OutputDirectory) Assert.Equal("d.exe", parsedArgs.OutputFileName) ' XML does not fall back on output directory. parsedArgs = DefaultParse({"/doc:b.xml", "/out:c\d.exe", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\abc\def\baz\b.xml", parsedArgs.DocumentationPath) Assert.Equal("C:\abc\def\baz\c", parsedArgs.OutputDirectory) Assert.Equal("d.exe", parsedArgs.OutputFileName) End Sub <Fact> Public Sub ParseDocMultiple() Const baseDirectory As String = "C:\abc\def\baz" Dim parsedArgs = DefaultParse({"/doc+", "/doc-", "/doc+", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) parsedArgs = DefaultParse({"/doc-", "/doc+", "/doc-", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(DocumentationMode.None, parsedArgs.ParseOptions.DocumentationMode) Assert.Null(parsedArgs.DocumentationPath) parsedArgs = DefaultParse({"/doc:a.xml", "/doc-", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(DocumentationMode.None, parsedArgs.ParseOptions.DocumentationMode) Assert.Null(parsedArgs.DocumentationPath) parsedArgs = DefaultParse({"/doc:abc.xml", "/doc+", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) parsedArgs = DefaultParse({"/doc-", "/doc:a.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) parsedArgs = DefaultParse({"/doc+", "/doc:a.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) End Sub <Fact> Public Sub ParseErrorLog() Const baseDirectory As String = "C:\abc\def\baz" Dim parsedArgs = DefaultParse({"/errorlog:", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) parsedArgs = DefaultParse({"/errorlog", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Should preserve fully qualified paths parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path) Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Should handle quotes parsedArgs = DefaultParse({"/errorlog:""C:\My Folder\MyBinary.xml""", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\My Folder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path) Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Quote after a \ is treated as an escape parsedArgs = DefaultParse({"/errorlog:C:\""My Folder""\MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("C:""My Folder\MyBinary.xml").WithLocation(1, 1)) ' Should expand partially qualified paths parsedArgs = DefaultParse({"/errorlog:MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.ErrorLogOptions.Path) ' Should expand partially qualified paths parsedArgs = DefaultParse({"/errorlog:..\MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\abc\def\MyBinary.xml", parsedArgs.ErrorLogOptions.Path) Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' drive-relative path: Dim currentDrive As Char = Directory.GetCurrentDirectory()(0) Dim filePath = currentDrive + ":a.xml" parsedArgs = DefaultParse({"/errorlog:" + filePath, "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(filePath)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' UNC parsedArgs = DefaultParse({"/errorlog:\\server\share\file.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("\\server\share\file.xml", parsedArgs.ErrorLogOptions.Path) Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Parses SARIF version. parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml,version=2", "a.cs"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path) Assert.Equal(SarifVersion.Sarif2, parsedArgs.ErrorLogOptions.SarifVersion) Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Invalid SARIF version. parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml,version=42", "a.cs"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_BadSwitchValue).WithArguments("C:\MyFolder\MyBinary.xml,version=42", "errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml,version=1.0.0", "a.cs"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_BadSwitchValue).WithArguments("C:\MyFolder\MyBinary.xml,version=1.0.0", "errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml,version=2.1.0", "a.cs"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_BadSwitchValue).WithArguments("C:\MyFolder\MyBinary.xml,version=2.1.0", "errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Invalid errorlog qualifier. parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml,invalid=42", "a.cs"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_BadSwitchValue).WithArguments("C:\MyFolder\MyBinary.xml,invalid=42", "errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Too many errorlog qualifiers. parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml,version=2,version=2", "a.cs"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_BadSwitchValue).WithArguments("C:\MyFolder\MyBinary.xml,version=2,version=2", "errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) End Sub <Fact> Public Sub ParseErrorLogAndOut() Const baseDirectory As String = "C:\abc\def\baz" ' Can specify separate directories for binary and error log output. Dim parsedArgs = DefaultParse({"/errorlog:a\b.xml", "/out:c\d.exe", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\abc\def\baz\a\b.xml", parsedArgs.ErrorLogOptions.Path) Assert.Equal("C:\abc\def\baz\c", parsedArgs.OutputDirectory) Assert.Equal("d.exe", parsedArgs.OutputFileName) ' error log does not fall back on output directory. parsedArgs = DefaultParse({"/errorlog:b.xml", "/out:c\d.exe", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\abc\def\baz\b.xml", parsedArgs.ErrorLogOptions.Path) Assert.Equal("C:\abc\def\baz\c", parsedArgs.OutputDirectory) Assert.Equal("d.exe", parsedArgs.OutputFileName) End Sub <Fact> Public Sub KeyContainerAndKeyFile() ' KEYCONTAINER Dim parsedArgs = DefaultParse({"/KeyContainer:key-cont-name", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("key-cont-name", parsedArgs.CompilationOptions.CryptoKeyContainer) parsedArgs = DefaultParse({"/KEYcontainer", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keycontainer", ":<string>")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer) parsedArgs = DefaultParse({"/keycontainer-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/keycontainer-")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer) parsedArgs = DefaultParse({"/keycontainer:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keycontainer", ":<string>")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer) parsedArgs = DefaultParse({"/keycontainer: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keycontainer", ":<string>")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer) ' KEYFILE parsedArgs = DefaultParse({"/keyfile:\somepath\s""ome Fil""e.goo.bar", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("\somepath\some File.goo.bar", parsedArgs.CompilationOptions.CryptoKeyFile) parsedArgs = DefaultParse({"/keyFile", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keyfile", ":<file>")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile) parsedArgs = DefaultParse({"/keyfile-", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/keyfile-")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile) parsedArgs = DefaultParse({"/keyfile: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keyfile", ":<file>")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile) ' default value parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Nothing, parsedArgs.CompilationOptions.CryptoKeyContainer) Assert.Equal(Nothing, parsedArgs.CompilationOptions.CryptoKeyFile) ' keyfile/keycontainer conflicts parsedArgs = DefaultParse({"/keycontainer:a", "/keyfile:b", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Nothing, parsedArgs.CompilationOptions.CryptoKeyContainer) Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyFile) ' keyfile/keycontainer conflicts parsedArgs = DefaultParse({"/keyfile:b", "/keycontainer:a", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyContainer) Assert.Equal(Nothing, parsedArgs.CompilationOptions.CryptoKeyFile) End Sub <Fact, WorkItem(530088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530088")> Public Sub Platform() ' test recognizing all options Dim parsedArgs = DefaultParse({"/platform:X86", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.X86, parsedArgs.CompilationOptions.Platform) parsedArgs = DefaultParse({"/platform:x64", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.X64, parsedArgs.CompilationOptions.Platform) parsedArgs = DefaultParse({"/platform:itanium", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.Itanium, parsedArgs.CompilationOptions.Platform) parsedArgs = DefaultParse({"/platform:anycpu", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.AnyCpu, parsedArgs.CompilationOptions.Platform) parsedArgs = DefaultParse({"/platform:anycpu32bitpreferred", "/t:exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform) parsedArgs = DefaultParse({"/platform:anycpu32bitpreferred", "/t:appcontainerexe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform) parsedArgs = DefaultParse({"/platform:arm", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.Arm, parsedArgs.CompilationOptions.Platform) ' test default (AnyCPU) parsedArgs = DefaultParse({"/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.AnyCpu, parsedArgs.CompilationOptions.Platform) ' test missing parsedArgs = DefaultParse({"/platform:", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("platform", ":<string>")) parsedArgs = DefaultParse({"/platform", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("platform", ":<string>")) parsedArgs = DefaultParse({"/platform+", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/platform+")) ' TODO: Dev11 reports ERR_ArgumentRequired ' test illegal input parsedArgs = DefaultParse({"/platform:abcdef", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("platform", "abcdef")) ' test overriding parsedArgs = DefaultParse({"/platform:anycpu32bitpreferred", "/platform:anycpu", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.AnyCpu, parsedArgs.CompilationOptions.Platform) ' test illegal parsedArgs = DefaultParse({"/platform:anycpu32bitpreferred", "/t:library", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_LibAnycpu32bitPreferredConflict).WithArguments("Platform", "AnyCpu32BitPreferred").WithLocation(1, 1)) parsedArgs = DefaultParse({"/platform:anycpu", "/platform:anycpu32bitpreferred", "/target:winmdobj", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_LibAnycpu32bitPreferredConflict).WithArguments("Platform", "AnyCpu32BitPreferred").WithLocation(1, 1)) End Sub <Fact()> Public Sub FileAlignment() ' test recognizing all options Dim parsedArgs = DefaultParse({"/filealign:512", "a.vb"}, _baseDirectory) Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:1024", "a.vb"}, _baseDirectory) Assert.Equal(1024, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:2048", "a.vb"}, _baseDirectory) Assert.Equal(2048, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:4096", "a.vb"}, _baseDirectory) Assert.Equal(4096, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:8192", "a.vb"}, _baseDirectory) Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment) ' test oct values parsedArgs = DefaultParse({"/filealign:01000", "a.vb"}, _baseDirectory) Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:02000", "a.vb"}, _baseDirectory) Assert.Equal(1024, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:04000", "a.vb"}, _baseDirectory) Assert.Equal(2048, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:010000", "a.vb"}, _baseDirectory) Assert.Equal(4096, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:020000", "a.vb"}, _baseDirectory) Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment) ' test hex values parsedArgs = DefaultParse({"/filealign:0x200", "a.vb"}, _baseDirectory) Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:0x400", "a.vb"}, _baseDirectory) Assert.Equal(1024, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:0x800", "a.vb"}, _baseDirectory) Assert.Equal(2048, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:0x1000", "a.vb"}, _baseDirectory) Assert.Equal(4096, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:0x2000", "a.vb"}, _baseDirectory) Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment) ' test default (no value) parsedArgs = DefaultParse({"/platform:x86", "a.vb"}, _baseDirectory) Assert.Equal(0, parsedArgs.EmitOptions.FileAlignment) ' test missing parsedArgs = DefaultParse({"/filealign:", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("filealign", ":<number>")) ' test illegal parsedArgs = DefaultParse({"/filealign:0", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("filealign", "0")) parsedArgs = DefaultParse({"/filealign:0x", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("filealign", "0x")) parsedArgs = DefaultParse({"/filealign:0x0", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("filealign", "0x0")) parsedArgs = DefaultParse({"/filealign:-1", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("filealign", "-1")) parsedArgs = DefaultParse({"/filealign:-0x100", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("filealign", "-0x100")) End Sub <Fact()> Public Sub RemoveIntChecks() Dim parsedArgs = DefaultParse({"/removeintcheckS", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.False(parsedArgs.CompilationOptions.CheckOverflow) parsedArgs = DefaultParse({"/removeintcheckS+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.False(parsedArgs.CompilationOptions.CheckOverflow) parsedArgs = DefaultParse({"/removeintcheckS-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.CompilationOptions.CheckOverflow) parsedArgs = DefaultParse({"/removeintchecks+", "/removeintchecks-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.CompilationOptions.CheckOverflow) parsedArgs = DefaultParse({"/removeintchecks:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("removeintchecks")) parsedArgs = DefaultParse({"/removeintchecks:+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("removeintchecks")) parsedArgs = DefaultParse({"/removeintchecks+:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("removeintchecks")) End Sub <Fact()> Public Sub BaseAddress() ' This test is about what passes the parser. Even if a value was accepted by the parser it might not be considered ' as a valid base address later on (e.g. values >0x8000). ' test decimal values being treated as hex Dim parsedArgs = DefaultParse({"/baseaddress:0", "a.vb"}, _baseDirectory) Assert.Equal(CType(0, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:1024", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H1024, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:2048", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H2048, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:4096", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H4096, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:8192", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H8192, ULong), parsedArgs.EmitOptions.BaseAddress) ' test hex values being treated as hex parsedArgs = DefaultParse({"/baseaddress:0x200", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H200, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:0x400", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H400, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:0x800", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H800, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:0x1000", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H1000, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:0xFFFFFFFFFFFFFFFF", "a.vb"}, _baseDirectory) Assert.Equal(ULong.MaxValue, parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:FFFFFFFFFFFFFFFF", "a.vb"}, _baseDirectory) Assert.Equal(ULong.MaxValue, parsedArgs.EmitOptions.BaseAddress) ' test octal values being treated as hex parsedArgs = DefaultParse({"/baseaddress:00", "a.vb"}, _baseDirectory) Assert.Equal(CType(0, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:01024", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H1024, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:02048", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H2048, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:04096", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H4096, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:08192", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H8192, ULong), parsedArgs.EmitOptions.BaseAddress) ' test default (no value) parsedArgs = DefaultParse({"/platform:x86", "a.vb"}, _baseDirectory) Assert.Equal(CType(0, ULong), parsedArgs.EmitOptions.BaseAddress) ' test missing parsedArgs = DefaultParse({"/baseaddress:", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("baseaddress", ":<number>")) ' test illegal parsedArgs = DefaultParse({"/baseaddress:0x10000000000000000", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("baseaddress", "0x10000000000000000")) parsedArgs = DefaultParse({"/BASEADDRESS:-1", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("baseaddress", "-1")) parsedArgs = DefaultParse({"/BASEADDRESS:" + ULong.MaxValue.ToString, "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("baseaddress", ULong.MaxValue.ToString)) End Sub <Fact()> Public Sub BinaryFile() Dim binaryPath = Temp.CreateFile().WriteAllBytes(TestMetadata.ResourcesNet451.mscorlib).Path Dim outWriter As New StringWriter() Dim exitCode As Integer = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/preferreduilang:en", binaryPath}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2015: the file '" + binaryPath + "' is not a text file", outWriter.ToString.Trim()) CleanupAllGeneratedFiles(binaryPath) End Sub <Fact()> Public Sub AddModule() Dim parsedArgs = DefaultParse({"/nostdlib", "/vbruntime-", "/addMODULE:c:\,d:\x\y\z,abc,,", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(3, parsedArgs.MetadataReferences.Length) Assert.Equal("c:\", parsedArgs.MetadataReferences(0).Reference) Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences(0).Properties.Kind) Assert.Equal("d:\x\y\z", parsedArgs.MetadataReferences(1).Reference) Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences(1).Properties.Kind) Assert.Equal("abc", parsedArgs.MetadataReferences(2).Reference) Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences(2).Properties.Kind) Assert.False(parsedArgs.MetadataReferences(0).Reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)) Assert.False(parsedArgs.MetadataReferences(1).Reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)) Assert.False(parsedArgs.MetadataReferences(2).Reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)) Assert.True(parsedArgs.DefaultCoreLibraryReference.Value.Reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)) Assert.Equal(MetadataImageKind.Assembly, parsedArgs.DefaultCoreLibraryReference.Value.Properties.Kind) parsedArgs = DefaultParse({"/ADDMODULE", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("addmodule", ":<file_list>")) parsedArgs = DefaultParse({"/addmodule:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("addmodule", ":<file_list>")) parsedArgs = DefaultParse({"/addmodule+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/addmodule+")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact()> Public Sub LibPathsAndLibEnvVariable() Dim parsedArgs = DefaultParse({"/libpath:c:\,d:\x\y\z,abc,,", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertReferencePathsEqual(parsedArgs.ReferencePaths, Nothing, "c:\", "d:\x\y\z", Path.Combine(_baseDirectory, "abc")) parsedArgs = DefaultParse({"/lib:c:\Windows", "/libpaths:abc\def, , , ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertReferencePathsEqual(parsedArgs.ReferencePaths, Nothing, "c:\Windows", Path.Combine(_baseDirectory, "abc\def")) parsedArgs = DefaultParse({"/libpath", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("libpath", ":<path_list>")) parsedArgs = DefaultParse({"/libpath:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("libpath", ":<path_list>")) parsedArgs = DefaultParse({"/libpath+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/libpath+")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact(), WorkItem(546005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546005")> Public Sub LibPathsAndLibEnvVariable_Relative_vbc() Dim tempFolder = Temp.CreateDirectory() Dim baseDirectory = tempFolder.ToString() Dim subFolder = tempFolder.CreateDirectory("temp") Dim subDirectory = subFolder.ToString() Dim src = Temp.CreateFile("a.vb") src.WriteAllText("Imports System") Dim outWriter As New StringWriter() Dim exitCode As Integer = New MockVisualBasicCompiler(Nothing, subDirectory, {"/nologo", "/t:library", "/out:abc.xyz", src.ToString()}).Run(outWriter, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", outWriter.ToString().Trim()) outWriter = New StringWriter() exitCode = New MockVisualBasicCompiler(Nothing, baseDirectory, {"/nologo", "/libpath:temp", "/r:abc.xyz.dll", "/t:library", src.ToString()}).Run(outWriter, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", outWriter.ToString().Trim()) CleanupAllGeneratedFiles(src.Path) End Sub <Fact()> Public Sub UnableWriteOutput() Dim tempFolder = Temp.CreateDirectory() Dim baseDirectory = tempFolder.ToString() Dim subFolder = tempFolder.CreateDirectory("temp.dll") Dim src = Temp.CreateFile("a.vb") src.WriteAllText("Imports System") Dim outWriter As New StringWriter() Dim exitCode As Integer = New MockVisualBasicCompiler(Nothing, baseDirectory, {"/nologo", "/preferreduilang:en", "/t:library", "/out:" & subFolder.ToString(), src.ToString()}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.True(outWriter.ToString().Contains("error BC2012: can't open '" & subFolder.ToString() & "' for writing: ")) ' Cannot create a file when that file already exists. CleanupAllGeneratedFiles(src.Path) End Sub <Fact()> Public Sub SdkPathAndLibEnvVariable() Dim parsedArgs = DefaultParse({"/libpath:c:lib2", "/sdkpath:<>,d:\sdk1", "/vbruntime*", "/nostdlib", "a.vb"}, _baseDirectory) ' invalid paths are ignored parsedArgs.Errors.Verify() AssertReferencePathsEqual(parsedArgs.ReferencePaths, "d:\sdk1") parsedArgs = DefaultParse({"/sdkpath:c:\Windows", "/sdkpath:d:\Windows", "/vbruntime*", "/nostdlib", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertReferencePathsEqual(parsedArgs.ReferencePaths, "d:\Windows") parsedArgs = DefaultParse({"/sdkpath:c:\Windows,d:\blah", "a.vb"}, _baseDirectory) AssertReferencePathsEqual(parsedArgs.ReferencePaths, "c:\Windows", "d:\blah") parsedArgs = DefaultParse({"/libpath:c:\Windows,d:\blah", "/sdkpath:c:\lib2", "a.vb"}, _baseDirectory) AssertReferencePathsEqual(parsedArgs.ReferencePaths, "c:\lib2", "c:\Windows", "d:\blah") parsedArgs = DefaultParse({"/sdkpath", "/vbruntime*", "/nostdlib", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("sdkpath", ":<path>")) parsedArgs = DefaultParse({"/sdkpath:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("sdkpath", ":<path>")) parsedArgs = DefaultParse({"/sdkpath+", "/vbruntime*", "/nostdlib", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/sdkpath+")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact()> Public Sub VbRuntime() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text> Imports Microsoft.VisualBasic Class C Dim a = vbLf Dim b = Loc End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /vbruntime /t:library " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> src.vb(5) : error BC30455: Argument not specified for parameter 'FileNumber' of 'Public Function Loc(FileNumber As Integer) As Long'. Dim b = Loc ~~~ </text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /vbruntime+ /t:library " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> src.vb(5) : error BC30455: Argument not specified for parameter 'FileNumber' of 'Public Function Loc(FileNumber As Integer) As Long'. Dim b = Loc ~~~ </text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /vbruntime* /t:library /r:System.dll " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> src.vb(5) : error BC30451: 'Loc' is not declared. It may be inaccessible due to its protection level. Dim b = Loc ~~~ </text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /vbruntime+ /vbruntime:abc /vbruntime* /t:library /r:System.dll " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> src.vb(5) : error BC30451: 'Loc' is not declared. It may be inaccessible due to its protection level. Dim b = Loc ~~~ </text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /vbruntime+ /vbruntime:abc /t:library " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> vbc : error BC2017: could not find library 'abc' </text>, output) Dim newVbCore = dir.CreateFile("Microsoft.VisualBasic.dll") newVbCore.WriteAllBytes(File.ReadAllBytes(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "Microsoft.VisualBasic.dll"))) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /vbruntime:" & newVbCore.ToString() & " /t:library " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> src.vb(5) : error BC30455: Argument not specified for parameter 'FileNumber' of 'Public Function Loc(FileNumber As Integer) As Long'. Dim b = Loc ~~~ </text>, output) CleanupAllGeneratedFiles(src.Path) End Sub <WorkItem(997208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997208")> <Fact> Public Sub VbRuntime02() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text> Imports Microsoft.VisualBasic Class C Dim a = vbLf Dim b = Loc End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /r:mscorlib.dll /vbruntime- /t:library /d:_MyType=\""Empty\"" " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> src.vb(2) : warning BC40056: Namespace or type specified in the Imports 'Microsoft.VisualBasic' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports Microsoft.VisualBasic ~~~~~~~~~~~~~~~~~~~~~ src.vb(4) : error BC30451: 'vbLf' is not declared. It may be inaccessible due to its protection level. Dim a = vbLf ~~~~ src.vb(5) : error BC30451: 'Loc' is not declared. It may be inaccessible due to its protection level. Dim b = Loc ~~~ </text>, output) CleanupAllGeneratedFiles(src.Path) End Sub <Fact()> Public Sub VbRuntimeEmbeddedIsIncompatibleWithNetModule() Dim opt = TestOptions.ReleaseModule opt = opt.WithEmbedVbCoreRuntime(True) opt.Errors.Verify(Diagnostic(ERRID.ERR_VBCoreNetModuleConflict)) CreateCompilationWithMscorlib40AndVBRuntime(<compilation><file/></compilation>, opt).GetDiagnostics().Verify(Diagnostic(ERRID.ERR_VBCoreNetModuleConflict)) opt = opt.WithOutputKind(OutputKind.DynamicallyLinkedLibrary) opt.Errors.Verify() CreateCompilationWithMscorlib40AndVBRuntime(<compilation><file/></compilation>, opt).GetDiagnostics().Verify() End Sub <Fact()> Public Sub SdkPathInAction() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text> Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /sdkpath:l:\x /t:library " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text> vbc : error BC2017: could not find library 'Microsoft.VisualBasic.dll' </text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /r:mscorlib.dll /vbruntime- /sdkpath:c:folder /t:library " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text> vbc : error BC2017: could not find library 'mscorlib.dll' </text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /sdkpath:" & dir.Path & " /t:library " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text> vbc : error BC2017: could not find library 'Microsoft.VisualBasic.dll' </text>, output.Replace(dir.Path, "{SDKPATH}")) ' Create 'System.Runtime.dll' Dim sysRuntime = dir.CreateFile("System.Runtime.dll") sysRuntime.WriteAllBytes(File.ReadAllBytes(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "System.Runtime.dll"))) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /sdkpath:" & dir.Path & " /t:library " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text> vbc : error BC2017: could not find library 'Microsoft.VisualBasic.dll' </text>, output.Replace(dir.Path, "{SDKPATH}")) ' trash in 'System.Runtime.dll' sysRuntime.WriteAllBytes({0, 1, 2, 3, 4, 5}) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /sdkpath:" & dir.Path & " /t:library " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text> vbc : error BC2017: could not find library 'Microsoft.VisualBasic.dll' </text>, output.Replace(dir.Path, "{SDKPATH}")) ' Create 'mscorlib.dll' Dim msCorLib = dir.CreateFile("mscorlib.dll") msCorLib.WriteAllBytes(File.ReadAllBytes(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "mscorlib.dll"))) ' NOT: both libraries exist, but 'System.Runtime.dll' is invalid, so we need to pick up 'mscorlib.dll' output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /nostdlib /sdkpath:" & dir.Path & " /t:library /vbruntime* /r:" & Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "System.dll") & " " & src.ToString(), startFolder:=dir.Path) AssertOutput(<text></text>, output.Replace(dir.Path, "{SDKPATH}")) ' SUCCESSFUL BUILD with 'mscorlib.dll' and embedded VbCore File.Delete(sysRuntime.Path) ' NOTE: only 'mscorlib.dll' exists output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /nostdlib /sdkpath:" & dir.Path & " /t:library /vbruntime* /r:" & Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "System.dll") & " " & src.ToString(), startFolder:=dir.Path) AssertOutput(<text></text>, output.Replace(dir.Path, "{SDKPATH}")) File.Delete(msCorLib.Path) CleanupAllGeneratedFiles(src.Path) End Sub <WorkItem(598158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598158")> <Fact()> Public Sub MultiplePathsInSdkPath() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text> Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output As String = "" Dim subFolder1 = dir.CreateDirectory("fldr1") Dim subFolder2 = dir.CreateDirectory("fldr2") Dim sdkMultiPath = subFolder1.Path & "," & subFolder2.Path Dim cmd As String = " /nologo /preferreduilang:en /sdkpath:" & sdkMultiPath & " /t:library /r:" & Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "System.dll") & " " & src.ToString() Dim cmdNoStdLibNoRuntime As String = "/nostdlib /vbruntime* /r:mscorlib.dll /preferreduilang:en" & cmd ' NOTE: no 'mscorlib.dll' exists output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, cmdNoStdLibNoRuntime, startFolder:=dir.Path, expectedRetCode:=1) AssertOutput(<text>vbc : error BC2017: could not find library 'mscorlib.dll'</text>, output.Replace(dir.Path, "{SDKPATH}")) ' Create '<dir>\fldr2\mscorlib.dll' Dim msCorLib = subFolder2.CreateFile("mscorlib.dll") msCorLib.WriteAllBytes(File.ReadAllBytes(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "mscorlib.dll"))) ' NOTE: only 'mscorlib.dll' exists output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, cmdNoStdLibNoRuntime, startFolder:=dir.Path) AssertOutput(<text></text>, output.Replace(dir.Path, "{SDKPATH}")) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, cmd, startFolder:=dir.Path, expectedRetCode:=1) AssertOutput( <text> vbc : warning BC40049: Could not find standard library 'System.dll'. vbc : error BC2017: could not find library 'Microsoft.VisualBasic.dll' </text>, output.Replace(dir.Path, "{SDKPATH}")) File.Delete(msCorLib.Path) CleanupAllGeneratedFiles(src.Path) End Sub <Fact()> Public Sub NostdlibInAction() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text> Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /t:library " & src.ToString(), startFolder:=dir.Path, expectedRetCode:=1) Assert.Contains("error BC30002: Type 'Global.System.ComponentModel.EditorBrowsable' is not defined.", output, StringComparison.Ordinal) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /nostdlib /define:_MYTYPE=\""Empty\"" /t:library " & src.ToString(), startFolder:=dir.Path) AssertOutput(<text></text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /sdkpath:x:\ /vbruntime- /define:_MYTYPE=\""Empty\"" /t:library " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text> src.vb(2) : error BC30002: Type 'System.Void' is not defined. Class C ~~~~~~~ End Class ~~~~~~~~~ src.vb(2) : error BC31091: Import of type 'Object' from assembly or module 'src.dll' failed. Class C ~ </text>, output) CleanupAllGeneratedFiles(src.Path) End Sub Private Sub AssertOutput(expected As XElement, output As String, Optional fileName As String = "src.vb") AssertOutput(expected.Value, output, fileName) End Sub Private Sub AssertOutput(expected As String, output As String, Optional fileName As String = "src.vb") output = Regex.Replace(output, "^.*" & fileName, fileName, RegexOptions.Multiline) output = Regex.Replace(output, "\r\n\s*\r\n", vbCrLf) ' empty strings output = output.Trim() Assert.Equal(expected.Replace(vbLf, vbCrLf).Trim, output) End Sub <Fact()> Public Sub ResponsePathInSearchPath() Dim file = Temp.CreateDirectory().CreateFile("vb.rsp") file.WriteAllText("") Dim parsedArgs = DefaultParse({"/libpath:c:\lib2,", "@" & file.ToString(), "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertReferencePathsEqual(parsedArgs.ReferencePaths, Nothing, Path.GetDirectoryName(file.ToString()), "c:\lib2") CleanupAllGeneratedFiles(file.Path) End Sub Private Sub AssertReferencePathsEqual(refPaths As ImmutableArray(Of String), sdkPathOrNothing As String, ParamArray paths() As String) Assert.Equal(1 + paths.Length, refPaths.Length) Assert.Equal(If(sdkPathOrNothing, RuntimeEnvironment.GetRuntimeDirectory()), refPaths(0)) For i = 0 To paths.Count - 1 Assert.Equal(paths(i), refPaths(i + 1)) Next End Sub <Fact()> Public Sub HighEntropyVirtualAddressSpace() Dim parsedArgs = DefaultParse({"/highentropyva", "a.vb"}, _baseDirectory) Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace) parsedArgs = DefaultParse({"/highentropyva+", "a.vb"}, _baseDirectory) Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace) parsedArgs = DefaultParse({"/highentropyva-", "a.vb"}, _baseDirectory) Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace) parsedArgs = DefaultParse({"/highentropyva:+", "a.vb"}, _baseDirectory) Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace) Verify(parsedArgs.Errors, Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/highentropyva:+")) parsedArgs = DefaultParse({"/highentropyva:", "a.vb"}, _baseDirectory) Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace) Verify(parsedArgs.Errors, Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/highentropyva:")) parsedArgs = DefaultParse({"/highentropyva+ /highentropyva-", "a.vb"}, _baseDirectory) Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace) End Sub <Fact> Public Sub Win32ResQuotes() Dim responseFile As String() = { " /win32resource:d:\\""abc def""\a""b c""d\a.res" } Dim args = DefaultParse(VisualBasicCommandLineParser.ParseResponseLines(responseFile), "c:\") Assert.Equal("d:\abc def\ab cd\a.res", args.Win32ResourceFile) responseFile = { " /win32icon:d:\\""abc def""\a""b c""d\a.ico" } args = DefaultParse(VisualBasicCommandLineParser.ParseResponseLines(responseFile), "c:\") Assert.Equal("d:\abc def\ab cd\a.ico", args.Win32Icon) responseFile = { " /win32manifest:d:\\""abc def""\a""b c""d\a.manifest" } args = DefaultParse(VisualBasicCommandLineParser.ParseResponseLines(responseFile), "c:\") Assert.Equal("d:\abc def\ab cd\a.manifest", args.Win32Manifest) End Sub <Fact> Public Sub ResourceOnlyCompile() Dim parsedArgs = DefaultParse({"/resource:goo.vb,ed", "/out:e.dll"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/resource:goo.vb,ed"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSourcesOut)) End Sub <Fact> Public Sub OutputFileName1() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from name of first file. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:library"}, expectedOutputName:="p.dll") End Sub <Fact> Public Sub OutputFileName2() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:library", "/out:r.dll"}, expectedOutputName:="r.dll") End Sub <Fact> Public Sub OutputFileName3() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from name of first file. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:exe"}, expectedOutputName:="p.exe") End Sub <Fact> Public Sub OutputFileName4() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:exe", "/out:r.exe"}, expectedOutputName:="r.exe") End Sub <Fact> Public Sub OutputFileName5() Dim source1 = <![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from name of first file. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:exe", "/main:A"}, expectedOutputName:="p.exe") End Sub <Fact> Public Sub OutputFileName6() Dim source1 = <![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from name of first file. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:exe", "/main:B"}, expectedOutputName:="p.exe") End Sub <WorkItem(545773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545773")> <Fact> Public Sub OutputFileName7() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:library", "/out:goo"}, expectedOutputName:="goo.dll") End Sub <WorkItem(545773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545773")> <Fact> Public Sub OutputFileName8() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:library", "/out:goo. "}, expectedOutputName:="goo.dll") End Sub <WorkItem(545773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545773")> <Fact> Public Sub OutputFileName9() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:library", "/out:goo.a"}, expectedOutputName:="goo.a.dll") End Sub <WorkItem(545773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545773")> <Fact> Public Sub OutputFileName10() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:module", "/out:goo.a"}, expectedOutputName:="goo.a") End Sub <WorkItem(545773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545773")> <Fact> Public Sub OutputFileName11() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:module", "/out:goo.a . . . . "}, expectedOutputName:="goo.a") End Sub <WorkItem(545773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545773")> <Fact> Public Sub OutputFileName12() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:module", "/out:goo. . . . . "}, expectedOutputName:="goo.netmodule") End Sub <Fact> Public Sub OutputFileName13() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from name of first file. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:winmdobj"}, expectedOutputName:="p.winmdobj") End Sub <Fact> Public Sub OutputFileName14() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from name of first file. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:appcontainerexe"}, expectedOutputName:="p.exe") End Sub Private Sub CheckOutputFileName(source1 As XCData, source2 As XCData, inputName1 As String, inputName2 As String, commandLineArguments As String(), expectedOutputName As String) Dim dir = Temp.CreateDirectory() Dim file1 = dir.CreateFile(inputName1) file1.WriteAllText(source1.Value) Dim file2 = dir.CreateFile(inputName2) file2.WriteAllText(source2.Value) Dim outWriter As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, commandLineArguments.Concat({inputName1, inputName2}).ToArray()) Dim exitCode As Integer = vbc.Run(outWriter, Nothing) If exitCode <> 0 Then Console.WriteLine(outWriter.ToString()) Assert.Equal(0, exitCode) End If Assert.Equal(1, Directory.EnumerateFiles(dir.Path, "*" & PathUtilities.GetExtension(expectedOutputName)).Count()) Assert.Equal(1, Directory.EnumerateFiles(dir.Path, expectedOutputName).Count()) If System.IO.File.Exists(expectedOutputName) Then System.IO.File.Delete(expectedOutputName) End If CleanupAllGeneratedFiles(file1.Path) CleanupAllGeneratedFiles(file2.Path) End Sub Private Shared Sub AssertSpecificDiagnostics(expectedCodes As Integer(), expectedOptions As ReportDiagnostic(), args As VisualBasicCommandLineArguments) Dim actualOrdered = args.CompilationOptions.SpecificDiagnosticOptions.OrderBy(Function(entry) entry.Key) AssertEx.Equal( expectedCodes.Select(Function(i) MessageProvider.Instance.GetIdForErrorCode(i)), actualOrdered.Select(Function(entry) entry.Key)) AssertEx.Equal(expectedOptions, actualOrdered.Select(Function(entry) entry.Value)) End Sub <Fact> Public Sub WarningsOptions() ' Baseline Dim parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors parsedArgs = DefaultParse({"/warnaserror", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors+ parsedArgs = DefaultParse({"/warnaserror+", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors: parsedArgs = DefaultParse({"/warnaserror:", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors:42024,42025 parsedArgs = DefaultParse({"/warnaserror:42024,42025", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) AssertSpecificDiagnostics({42024, 42025}, {ReportDiagnostic.Error, ReportDiagnostic.Error}, parsedArgs) ' Test for /warnaserrors+: parsedArgs = DefaultParse({"/warnaserror+:", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors+:42024,42025 parsedArgs = DefaultParse({"/warnaserror+:42024,42025", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) AssertSpecificDiagnostics({42024, 42025}, {ReportDiagnostic.Error, ReportDiagnostic.Error}, parsedArgs) ' Test for /warnaserrors- parsedArgs = DefaultParse({"/warnaserror-", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors-: parsedArgs = DefaultParse({"/warnaserror-:", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors-:42024,42025 parsedArgs = DefaultParse({"/warnaserror-:42024,42025", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) AssertSpecificDiagnostics({42024, 42025}, {ReportDiagnostic.Default, ReportDiagnostic.Default}, parsedArgs) ' Test for /nowarn parsedArgs = DefaultParse({"/nowarn", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Suppress, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /nowarn: parsedArgs = DefaultParse({"/nowarn:", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /nowarn:42024,42025 parsedArgs = DefaultParse({"/nowarn:42024,42025", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) AssertSpecificDiagnostics({42024, 42025}, {ReportDiagnostic.Suppress, ReportDiagnostic.Suppress}, parsedArgs) End Sub <Fact()> Public Sub WarningsErrors() ' Previous versions of the compiler used to report warnings (BC2026, BC2014) ' whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. ' We no longer generate a warning in such cases. ' Test for /warnaserrors:1 Dim parsedArgs = DefaultParse({"/warnaserror:1", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() ' Test for /warnaserrors:abc parsedArgs = DefaultParse({"/warnaserror:abc", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() ' Test for /nowarn:1 parsedArgs = DefaultParse({"/nowarn:1", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() ' Test for /nowarn:abc parsedArgs = DefaultParse({"/nowarn:abc", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() End Sub <WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")> <Fact()> Public Sub CompilationWithWarnAsError() Dim source = <![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> ' Baseline without warning options (expect success) Dim exitCode As Integer = GetExitCode(source.Value, "a.vb", {}) Assert.Equal(0, exitCode) ' The case with /warnaserror (expect to be success, since there will be no warning) exitCode = GetExitCode(source.Value, "b.vb", {"/warnaserror"}) Assert.Equal(0, exitCode) ' The case with /warnaserror and /nowarn:1 (expect success) ' Note that even though the command line option has a warning, it is not going to become an error ' in order to avoid the halt of compilation. exitCode = GetExitCode(source.Value, "c.vb", {"/warnaserror", "/nowarn:1"}) Assert.Equal(0, exitCode) End Sub Public Function GetExitCode(source As String, fileName As String, commandLineArguments As String()) As Integer Dim dir = Temp.CreateDirectory() Dim file1 = dir.CreateFile(fileName) file1.WriteAllText(source) Dim outWriter As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, commandLineArguments.Concat({fileName}).ToArray()) Return vbc.Run(outWriter, Nothing) End Function <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_01() Dim source = <compilation> <file name="a.vb">Imports System Module Program Sub Main(args As String()) Dim x As Integer Dim yy As Integer Const zzz As Long = 0 End Sub Function goo() End Function End Module </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(5) : warning BC42024: Unused local variable: 'x'. Dim x As Integer ~ PATH(6) : warning BC42024: Unused local variable: 'yy'. Dim yy As Integer ~~ PATH(7) : warning BC42099: Unused local constant: 'zzz'. Const zzz As Long = 0 ~~~ PATH(11) : warning BC42105: Function 'goo' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Dim expected = ReplacePathAndVersionAndHash(result, file).Trim() Dim actual = output.ToString().Trim() Assert.Equal(expected, actual) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_02() ' It verifies the case where diagnostic does not have the associated location in it. Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices Module Module1 Delegate Sub delegateType() Sub main() Dim a As ArgIterator = Nothing Dim d As delegateType = AddressOf a.Goo End Sub <Extension()> _ Public Function Goo(ByVal x As ArgIterator) as Integer Return 1 End Function End Module ]]> </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(9) : error BC36640: Instance of restricted type 'ArgIterator' cannot be used in a lambda expression. Dim d As delegateType = AddressOf a.Goo ~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en", "-imports:System"}) vbc.Run(output, Nothing) Assert.Equal(ReplacePathAndVersionAndHash(result, file), output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_03() ' It verifies the case where the squiggles covers the error span with tabs in it. Dim source = "Module Module1" + vbCrLf + " Sub Main()" + vbCrLf + " Dim x As Integer = ""a" + vbTab + vbTab + vbTab + "b""c ' There is a tab in the string." + vbCrLf + " End Sub" + vbCrLf + "End Module" + vbCrLf Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(3) : error BC30201: Expression expected. Dim x As Integer = "a b"c ' There is a tab in the string. ~ PATH(3) : error BC30004: Character constant must contain exactly one character. Dim x As Integer = "a b"c ' There is a tab in the string. ~~~~~~~~~~~~~~~~~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Dim expected = ReplacePathAndVersionAndHash(result, file).Trim() Dim actual = output.ToString().Trim() Assert.Equal(expected, actual) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_04() ' It verifies the case where the squiggles covers multiple lines. Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Collections.Generic Module Module1 Sub Main() Dim i3 = From el In { 3, 33, 333 } Select el End Sub End Module ]]> </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(5) : error BC36593: Expression of type 'Integer()' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider. Dim i3 = From el In { ~ 3, 33, 333 ~~~~~~~~~~~~~~~~~~~~~~~~~~ } Select el ~~~~~~~~~~~~~~~~~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Assert.Equal(ReplacePathAndVersionAndHash(result, file), output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_05() ' It verifies the case where the squiggles covers multiple lines. Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Collections.Generic Module _ Module1 Sub Main() End Sub 'End Module ]]> </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(3) : error BC30625: 'Module' statement must end with a matching 'End Module'. Module _ ~~~~~~~~ Module1 ~~~~~~~~~~~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Assert.Equal(ReplacePathAndVersionAndHash(result, file), output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_06() ' It verifies the case where the squiggles covers the very long error span. Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Module Program Event eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee() Event eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee() Sub Main(args As String()) End Sub End Module ]]> </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(7) : error BC37220: Name 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeEventHandler' exceeds the maximum length allowed in metadata. Event eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Assert.Equal(ReplacePathAndVersionAndHash(result, file), output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_07() ' It verifies the case where the error is on the last line. Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() Console.WriteLine("Hello from VB") End Sub End Class]]> </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(4) : error BC30625: 'Module' statement must end with a matching 'End Module'. Module Module1 ~~~~~~~~~~~~~~ PATH(8) : error BC30460: 'End Class' must be preceded by a matching 'Class'. End Class ~~~~~~~~~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Assert.Equal(ReplacePathAndVersionAndHash(result, file), output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(531606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531606")> <Fact()> Public Sub ErrorMessageWithSquiggles_08() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() Dim i As system.Boolean, End Sub End Module ]]> </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(6) : error BC30203: Identifier expected. Dim i As system.Boolean, ~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Assert.Equal(ReplacePathAndVersionAndHash(result, file), output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub Private Shared Function ReplacePathAndVersionAndHash(result As XElement, file As TempFile) As String Return result.Value.Replace("PATH", file.Path).Replace("VERSION (HASH)", s_compilerVersion).Replace(vbLf, vbCrLf) End Function <WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")> <Fact()> Public Sub CompilationWithNonExistingOutPath() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/target:exe", "/preferreduilang:en", "/out:sub\a.exe"}) Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC2012: can't open '" + dir.Path + "\sub\a.exe' for writing", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")> <Fact()> Public Sub CompilationWithWrongOutPath_01() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en", "/target:exe", "/out:sub\"}) Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Dim message = output.ToString() Assert.Contains("error BC2032: File name", message, StringComparison.Ordinal) Assert.Contains("sub", message, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")> <Fact()> Public Sub CompilationWithWrongOutPath_02() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en", "/target:exe", "/out:sub\ "}) Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Dim message = output.ToString() Assert.Contains("error BC2032: File name", message, StringComparison.Ordinal) Assert.Contains("sub", message, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")> <Fact()> Public Sub CompilationWithWrongOutPath_03() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en", "/target:exe", "/out:aaa:\a.exe"}) Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC2032: File name 'aaa:\a.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")> <Fact()> Public Sub CompilationWithWrongOutPath_04() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en", "/target:exe", "/out: "}) Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC2006: option 'out' requires ':<file>'", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <Fact()> Public Sub SpecifyProperCodePage() ' Class <UTF8 Cyrillic Character> ' End Class Dim source() As Byte = { &H43, &H6C, &H61, &H73, &H73, &H20, &HD0, &H96, &HD, &HA, &H45, &H6E, &H64, &H20, &H43, &H6C, &H61, &H73, &H73 } Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllBytes(source) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /t:library " & file.ToString(), startFolder:=dir.Path) Assert.Equal("", output) ' Autodetected UTF8, NO ERROR output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /t:library /codepage:20127 " & file.ToString(), expectedRetCode:=1, startFolder:=dir.Path) ' 20127: US-ASCII ' 0xd0, 0x96 ==> 'Ж' ==> ERROR Dim expected = <result> a.vb(1) : error BC30203: Identifier expected. Class ?? ~ </result>.Value.Replace(vbLf, vbCrLf).Trim() Dim actual = Regex.Replace(output, "^.*a.vb", "a.vb", RegexOptions.Multiline).Trim() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub EmittedSubsystemVersion() Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText( <text> Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim comp = VisualBasicCompilation.Create("a.dll", options:=TestOptions.ReleaseDll) Dim peHeaders = New PEHeaders(comp.EmitToStream(New EmitOptions(subsystemVersion:=SubsystemVersion.Create(5, 1)))) Assert.Equal(5, peHeaders.PEHeader.MajorSubsystemVersion) Assert.Equal(1, peHeaders.PEHeader.MinorSubsystemVersion) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub DefaultManifestForExe() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim expectedManifest = <?xml version="1.0" encoding="utf-16"?> <ManifestResource Size="490"> <Contents><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource> CheckManifestXml(source, OutputKind.ConsoleApplication, explicitManifest:=Nothing, expectedManifest:=expectedManifest) End Sub <Fact> Public Sub DefaultManifestForDll() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> CheckManifestXml(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest:=Nothing, expectedManifest:=Nothing) End Sub <Fact> Public Sub DefaultManifestForModule() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> CheckManifestXml(source, OutputKind.NetModule, explicitManifest:=Nothing, expectedManifest:=Nothing) End Sub <Fact> Public Sub DefaultManifestForWinExe() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim expectedManifest = <?xml version="1.0" encoding="utf-16"?> <ManifestResource Size="490"> <Contents><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource> CheckManifestXml(source, OutputKind.WindowsApplication, explicitManifest:=Nothing, expectedManifest:=expectedManifest) End Sub <Fact> Public Sub DefaultManifestForAppContainerExe() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim expectedManifest = <?xml version="1.0" encoding="utf-16"?> <ManifestResource Size="490"> <Contents><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource> CheckManifestXml(source, OutputKind.WindowsRuntimeApplication, explicitManifest:=Nothing, expectedManifest:=expectedManifest) End Sub <Fact> Public Sub DefaultManifestForWinMDObj() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> CheckManifestXml(source, OutputKind.WindowsRuntimeMetadata, explicitManifest:=Nothing, expectedManifest:=Nothing) End Sub <Fact> Public Sub ExplicitManifestForExe() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim explicitManifest = <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="Test.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> Dim expectedManifest = <?xml version="1.0" encoding="utf-16"?> <ManifestResource Size="421"> <Contents><![CDATA[<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="Test.app" /> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource> CheckManifestXml(source, OutputKind.ConsoleApplication, explicitManifest, expectedManifest) End Sub <Fact> Public Sub ExplicitManifestResForDll() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim explicitManifest = <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="Test.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> Dim expectedManifest = <?xml version="1.0" encoding="utf-16"?> <ManifestResource Size="421"> <Contents><![CDATA[<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="Test.app" /> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource> CheckManifestXml(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest, expectedManifest) End Sub <Fact> Public Sub ExplicitManifestForModule() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim explicitManifest = <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="Test.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> CheckManifestXml(source, OutputKind.NetModule, explicitManifest, expectedManifest:=Nothing) End Sub <DllImport("kernel32.dll", SetLastError:=True)> Public Shared Function _ LoadLibraryEx(lpFileName As String, hFile As IntPtr, dwFlags As UInteger) As IntPtr End Function <DllImport("kernel32.dll", SetLastError:=True)> Public Shared Function _ FreeLibrary(hFile As IntPtr) As Boolean End Function Private Sub CheckManifestXml(source As XElement, outputKind As OutputKind, explicitManifest As XDocument, expectedManifest As XDocument) Dim dir = Temp.CreateDirectory() Dim sourceFile = dir.CreateFile("Test.cs").WriteAllText(source.Value) Dim outputFileName As String Dim target As String Select Case outputKind Case OutputKind.ConsoleApplication outputFileName = "Test.exe" target = "exe" Case OutputKind.WindowsApplication outputFileName = "Test.exe" target = "winexe" Case OutputKind.DynamicallyLinkedLibrary outputFileName = "Test.dll" target = "library" Case OutputKind.NetModule outputFileName = "Test.netmodule" target = "module" Case OutputKind.WindowsRuntimeMetadata outputFileName = "Test.winmdobj" target = "winmdobj" Case OutputKind.WindowsRuntimeApplication outputFileName = "Test.exe" target = "appcontainerexe" Case Else Throw TestExceptionUtilities.UnexpectedValue(outputKind) End Select Dim vbc As VisualBasicCompiler Dim manifestFile As TempFile If explicitManifest Is Nothing Then vbc = New MockVisualBasicCompiler(Nothing, dir.Path, { String.Format("/target:{0}", target), String.Format("/out:{0}", outputFileName), Path.GetFileName(sourceFile.Path) }) Else manifestFile = dir.CreateFile("Test.config").WriteAllText(explicitManifest.ToString()) vbc = New MockVisualBasicCompiler(Nothing, dir.Path, { String.Format("/target:{0}", target), String.Format("/out:{0}", outputFileName), String.Format("/win32manifest:{0}", Path.GetFileName(manifestFile.Path)), Path.GetFileName(sourceFile.Path) }) End If Assert.Equal(0, vbc.Run(New StringWriter(), Nothing)) Dim library As IntPtr = LoadLibraryEx(Path.Combine(dir.Path, outputFileName), IntPtr.Zero, 2) If library = IntPtr.Zero Then Throw New Win32Exception(Marshal.GetLastWin32Error()) End If Const resourceType As String = "#24" Dim resourceId As String = If(outputKind = OutputKind.DynamicallyLinkedLibrary, "#2", "#1") Dim manifestSize As UInteger = Nothing If expectedManifest Is Nothing Then Assert.Throws(Of Win32Exception)(Function() Win32Res.GetResource(library, resourceId, resourceType, manifestSize)) Else Dim manifestResourcePointer As IntPtr = Win32Res.GetResource(library, resourceId, resourceType, manifestSize) Dim actualManifest As String = Win32Res.ManifestResourceToXml(manifestResourcePointer, manifestSize) Assert.Equal(expectedManifest.ToString(), XDocument.Parse(actualManifest).ToString()) End If FreeLibrary(library) CleanupAllGeneratedFiles(sourceFile.Path) End Sub <WorkItem(530221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530221")> <WorkItem(5664, "https://github.com/dotnet/roslyn/issues/5664")> <ConditionalFact(GetType(IsEnglishLocal))> Public Sub Bug15538() ' The icacls command fails on our Helix machines And it appears to be related to the use of the $ in ' the username. ' https://github.com/dotnet/roslyn/issues/28836 If StringComparer.OrdinalIgnoreCase.Equals(Environment.UserDomainName, "WORKGROUP") Then Return End If Dim folder = Temp.CreateDirectory() Dim source As String = folder.CreateFile("src.vb").WriteAllText("").Path Dim ref As String = folder.CreateFile("ref.dll").WriteAllText("").Path Try Dim output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " & ref & " /inheritance:r /Q") Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()) output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " & ref & " /deny %USERDOMAIN%\%USERNAME%:(r,WDAC) /Q") Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()) output = ProcessUtilities.RunAndGetOutput("cmd", "/C """ & s_basicCompilerExecutable & """ /nologo /preferreduilang:en /r:" & ref & " /t:library " & source, expectedRetCode:=1) Assert.True(output.StartsWith("vbc : error BC31011: Unable to load referenced library '" & ref & "': Access to the path '" & ref & "' is denied.", StringComparison.Ordinal)) Finally Dim output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " & ref & " /reset /Q") Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()) File.Delete(ref) End Try CleanupAllGeneratedFiles(source) End Sub <WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")> <Fact()> Public Sub ResponseFilesWithNoconfig_01() Dim source As String = Temp.CreateFile().WriteAllText(<text> Imports System Module Module1 Sub Main() Dim x As Integer End Sub End Module </text>.Value).Path Dim rsp As String = Temp.CreateFile().WriteAllText(<text> /warnaserror </text>.Value).Path ' Checks the base case without /noconfig (expect to see error) Dim vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en"}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC42024: Unused local variable: 'x'.", output.ToString(), StringComparison.Ordinal) ' Checks the base case with /noconfig (expect to see warning, instead of error) vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en", "/noconfig"}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC42024: Unused local variable: 'x'.", output.ToString(), StringComparison.Ordinal) ' Checks the base case with /NOCONFIG (expect to see warning, instead of error) vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en", "/NOCONFIG"}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC42024: Unused local variable: 'x'.", output.ToString(), StringComparison.Ordinal) ' Checks the base case with -noconfig (expect to see warning, instead of error) vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en", "-noconfig"}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC42024: Unused local variable: 'x'.", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(rsp) End Sub <WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")> <Fact()> Public Sub ResponseFilesWithNoconfig_02() Dim source As String = Temp.CreateFile().WriteAllText(<text> Imports System Module Module1 Sub Main() End Sub End Module </text>.Value).Path Dim rsp As String = Temp.CreateFile().WriteAllText(<text> /noconfig </text>.Value).Path ' Checks the case with /noconfig inside the response file (expect to see warning) Dim vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en"}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC2025: ignoring /noconfig option because it was specified in a response file", output.ToString(), StringComparison.Ordinal) ' Checks the case with /noconfig inside the response file as along with /nowarn (expect to see warning) vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en", "/nowarn"}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC2025: ignoring /noconfig option because it was specified in a response file", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(rsp) End Sub <WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")> <Fact()> Public Sub ResponseFilesWithNoconfig_03() Dim source As String = Temp.CreateFile().WriteAllText(<text> Imports System Module Module1 Sub Main() End Sub End Module </text>.Value).Path Dim rsp As String = Temp.CreateFile().WriteAllText(<text> /NOCONFIG </text>.Value).Path ' Checks the case with /noconfig inside the response file (expect to see warning) Dim vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en"}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC2025: ignoring /noconfig option because it was specified in a response file", output.ToString(), StringComparison.Ordinal) ' Checks the case with /NOCONFIG inside the response file as along with /nowarn (expect to see warning) vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en", "/nowarn"}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC2025: ignoring /noconfig option because it was specified in a response file", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(rsp) End Sub <WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")> <Fact()> Public Sub ResponseFilesWithNoconfig_04() Dim source As String = Temp.CreateFile().WriteAllText(<text> Imports System Module Module1 Sub Main() End Sub End Module </text>.Value).Path Dim rsp As String = Temp.CreateFile().WriteAllText(<text> -noconfig </text>.Value).Path ' Checks the case with /noconfig inside the response file (expect to see warning) Dim vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en"}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC2025: ignoring /noconfig option because it was specified in a response file", output.ToString(), StringComparison.Ordinal) ' Checks the case with -noconfig inside the response file as along with /nowarn (expect to see warning) vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en", "/nowarn"}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC2025: ignoring /noconfig option because it was specified in a response file", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(rsp) End Sub <WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")> <Fact()> Public Sub ResponseFilesWithEmptyAliasReference() Dim source As String = Temp.CreateFile().WriteAllText(<text> Imports System </text>.Value).Path Dim rsp As String = Temp.CreateFile().WriteAllText(<text> -nologo /r:a="""" </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en"}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2017: could not find library 'a='", output.ToString().Trim()) CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(rsp) End Sub <WorkItem(546031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546031")> <WorkItem(546032, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546032")> <WorkItem(546033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546033")> <Fact()> Public Sub InvalidDefineSwitch() Dim source As String = Temp.CreateFile().WriteAllText(<text> Imports System </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define", source}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'define' requires ':<symbol_list>'", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'define' requires ':<symbol_list>'", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define: ", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'define' requires ':<symbol_list>'", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:_,", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant '_ ^^ ^^ ' is not valid: Identifier expected.", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:_a,", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:_ a,", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant '_ ^^ ^^ a' is not valid: Identifier expected.", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:a,_,b", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant '_ ^^ ^^ ' is not valid: Identifier expected.", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:_", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant '_ ^^ ^^ ' is not valid: Identifier expected.", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:_ ", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant '_ ^^ ^^ ' is not valid: Identifier expected.", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:a,_", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant '_ ^^ ^^ ' is not valid: Identifier expected.", output.ToString().Trim()) CleanupAllGeneratedFiles(source) End Sub Private Function GetDefaultResponseFilePath() As String Return Temp.CreateFile().WriteAllBytes(GetType(CommandLineTests).Assembly.GetManifestResourceStream("vbc.rsp").ReadAllBytes()).Path End Function <Fact> Public Sub DefaultResponseFile() Dim defaultResponseFile = GetDefaultResponseFilePath() Assert.True(File.Exists(defaultResponseFile)) Dim vbc As New MockVisualBasicCompiler(defaultResponseFile, _baseDirectory, {}) ' VB includes these by default, with or without the default response file. Dim corlibLocation = GetType(Object).Assembly.Location Dim corlibDir = Path.GetDirectoryName(corlibLocation) Dim systemLocation = Path.Combine(corlibDir, "System.dll") Dim msvbLocation = Path.Combine(corlibDir, "Microsoft.VisualBasic.dll") Assert.Equal(vbc.Arguments.MetadataReferences.Select(Function(r) r.Reference), { "Accessibility.dll", "System.Configuration.dll", "System.Configuration.Install.dll", "System.Data.dll", "System.Data.OracleClient.dll", "System.Deployment.dll", "System.Design.dll", "System.DirectoryServices.dll", "System.dll", "System.Drawing.Design.dll", "System.Drawing.dll", "System.EnterpriseServices.dll", "System.Management.dll", "System.Messaging.dll", "System.Runtime.Remoting.dll", "System.Runtime.Serialization.Formatters.Soap.dll", "System.Security.dll", "System.ServiceProcess.dll", "System.Transactions.dll", "System.Web.dll", "System.Web.Mobile.dll", "System.Web.RegularExpressions.dll", "System.Web.Services.dll", "System.Windows.Forms.dll", "System.XML.dll", "System.Workflow.Activities.dll", "System.Workflow.ComponentModel.dll", "System.Workflow.Runtime.dll", "System.Runtime.Serialization.dll", "System.ServiceModel.dll", "System.Core.dll", "System.Xml.Linq.dll", "System.Data.Linq.dll", "System.Data.DataSetExtensions.dll", "System.Web.Extensions.dll", "System.Web.Extensions.Design.dll", "System.ServiceModel.Web.dll", systemLocation, msvbLocation }, StringComparer.OrdinalIgnoreCase) Assert.Equal(vbc.Arguments.CompilationOptions.GlobalImports.Select(Function(i) i.Name), { "System", "Microsoft.VisualBasic", "System.Linq", "System.Xml.Linq" }) Assert.True(vbc.Arguments.CompilationOptions.OptionInfer) End Sub <Fact> Public Sub DefaultResponseFileNoConfig() Dim defaultResponseFile = GetDefaultResponseFilePath() Assert.True(File.Exists(defaultResponseFile)) Dim vbc As New MockVisualBasicCompiler(defaultResponseFile, _baseDirectory, {"/noconfig"}) ' VB includes these by default, with or without the default response file. Dim corlibLocation = GetType(Object).Assembly.Location Dim corlibDir = Path.GetDirectoryName(corlibLocation) Dim systemLocation = Path.Combine(corlibDir, "System.dll") Dim msvbLocation = Path.Combine(corlibDir, "Microsoft.VisualBasic.dll") Assert.Equal(vbc.Arguments.MetadataReferences.Select(Function(r) r.Reference), { systemLocation, msvbLocation }, StringComparer.OrdinalIgnoreCase) Assert.Equal(0, vbc.Arguments.CompilationOptions.GlobalImports.Count) Assert.False(vbc.Arguments.CompilationOptions.OptionInfer) End Sub <Fact(), WorkItem(546114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546114")> Public Sub TestFilterCommandLineDiagnostics() Dim source As String = Temp.CreateFile().WriteAllText(<text> Module Module1 Function blah() As Integer End Function Sub Main() End Sub End Module </text>.Value).Path ' Previous versions of the compiler used to report warnings (BC2026) ' whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. ' We no longer generate a warning in such cases. Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/preferreduilang:en", "/blah", "/nowarn:2007,42353,1234,2026", source}) Dim output = New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("vbc : warning BC2007: unrecognized option '/blah'; ignored", output.ToString().Trim()) CleanupAllGeneratedFiles(source) End Sub <WorkItem(546305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546305")> <Fact()> Public Sub Bug15539() Dim source As String = Temp.CreateFile().WriteAllText(<text> Module Module1 Sub Main() End Sub End Module </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/preferreduilang:en", "/define:I(", source}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant 'I ^^ ^^ ' is not valid: End of statement expected.", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/preferreduilang:en", "/define:I*", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant 'I ^^ ^^ ' is not valid: End of statement expected.", output.ToString().Trim()) End Sub <Fact()> Public Sub TestImportsWithQuotes() Dim errors As IEnumerable(Of DiagnosticInfo) = Nothing Dim [imports] = "System,""COLL = System.Collections"",System.Diagnostics,""COLLGEN = System.Collections.Generic""" Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/imports:" + [imports]}) Assert.Equal(4, vbc.Arguments.CompilationOptions.GlobalImports.Count) Assert.Equal("System", vbc.Arguments.CompilationOptions.GlobalImports(0).Name) Assert.Equal("COLL = System.Collections", vbc.Arguments.CompilationOptions.GlobalImports(1).Name) Assert.Equal("System.Diagnostics", vbc.Arguments.CompilationOptions.GlobalImports(2).Name) Assert.Equal("COLLGEN = System.Collections.Generic", vbc.Arguments.CompilationOptions.GlobalImports(3).Name) End Sub <Fact()> Public Sub TestCommandLineSwitchThatNoLongerAreImplemented() ' These switches are no longer implemented and should fail silently ' the switches have various arguments that can be used Dim source As String = Temp.CreateFile().WriteAllText(<text> Module Module1 Sub Main() End Sub End Module </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/netcf", source}) Dim output = New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/bugreport", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/bugreport:test.dmp", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/errorreport", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/errorreport:prompt", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/errorreport:queue", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/errorreport:send", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/errorreport:", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/bugreport:", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/novbruntimeref", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) ' Just to confirm case insensitive vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/errorreport:PROMPT", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) CleanupAllGeneratedFiles(source) End Sub <WorkItem(531263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531263")> <Fact> Public Sub EmptyFileName() Dim outWriter As New StringWriter() Dim exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {""}).Run(outWriter, Nothing) Assert.NotEqual(0, exitCode) ' error BC2032: File name '' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Assert.Contains("BC2032", outWriter.ToString(), StringComparison.Ordinal) End Sub <WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")> <Fact> Public Sub PreferredUILang() Dim outWriter As New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Contains("BC2006", outWriter.ToString(), StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Contains("BC2006", outWriter.ToString(), StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:zz"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Contains("BC2038", outWriter.ToString(), StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:en-zz"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Contains("BC2038", outWriter.ToString(), StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:en-US"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.DoesNotContain("BC2038", outWriter.ToString(), StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:de"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.DoesNotContain("BC2038", outWriter.ToString(), StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:de-AT"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.DoesNotContain("BC2038", outWriter.ToString(), StringComparison.Ordinal) End Sub <Fact, WorkItem(650083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650083")> Public Sub ReservedDeviceNameAsFileName() ' Source file name Dim parsedArgs = DefaultParse({"/t:library", "con.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/out:com1.exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("\\.\com1").WithLocation(1, 1)) parsedArgs = DefaultParse({"/doc:..\lpt2.xml", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments("..\lpt2.xml", "The system cannot find the path specified").WithLocation(1, 1)) parsedArgs = DefaultParse({"/SdkPath:..\aux", "com.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_CannotFindStandardLibrary1).WithArguments("System.dll").WithLocation(1, 1), Diagnostic(ERRID.ERR_LibNotFound).WithArguments("Microsoft.VisualBasic.dll").WithLocation(1, 1)) End Sub <Fact()> Public Sub ReservedDeviceNameAsFileName2() Dim source As String = Temp.CreateFile().WriteAllText(<text> Module Module1 Sub Main() End Sub End Module </text>.Value).Path ' Make sure these reserved device names don't affect compiler Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/r:.\com3.dll", "/preferreduilang:en", source}) Dim output = New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC2017: could not find library '.\com3.dll'", output.ToString(), StringComparison.Ordinal) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/preferreduilang:en", "/link:prn.dll", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC2017: could not find library 'prn.dll'", output.ToString(), StringComparison.Ordinal) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"@aux.rsp", "/preferreduilang:en", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Dim errMessage = output.ToString().Trim() Assert.Contains("error BC2011: unable to open response file", errMessage, StringComparison.Ordinal) Assert.Contains("aux.rsp", errMessage, StringComparison.Ordinal) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/preferreduilang:en", "/vbruntime:..\con.dll", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC2017: could not find library '..\con.dll'", output.ToString(), StringComparison.Ordinal) ' Native VB compiler also ignore invalid lib paths vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/LibPath:lpt1,Lpt2,LPT9", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) CleanupAllGeneratedFiles(source) End Sub <Fact, WorkItem(574361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/574361")> Public Sub LangVersionForOldBC36716() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Collections Friend Module AutoPropAttributesmod Class AttrInThisAsmAttribute Inherits Attribute Public Property Prop() As Integer End Class Class HasProps <CompilerGenerated()> Public Property Scen1() As <CompilerGenerated()> Func(Of String) <CLSCompliant(False), Obsolete("obsolete message!")> <AttrInThisAsmAttribute()> Public Property Scen2() As String End Class End Module ]]> </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /t:library /langversion:9 /preferreduilang:en " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text><![CDATA[ src.vb(8) : error BC36716: Visual Basic 9.0 does not support auto-implemented properties. Public Property Prop() As Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ src.vb(12) : error BC36716: Visual Basic 9.0 does not support auto-implemented properties. <CompilerGenerated()> ~~~~~~~~~~~~~~~~~~~~~ Public Property Scen1() As <CompilerGenerated()> Func(Of String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ src.vb(12) : error BC36716: Visual Basic 9.0 does not support implicit line continuation. <CompilerGenerated()> ~~~~~~~~~~~~~~~~~~~~~ Public Property Scen1() As <CompilerGenerated()> Func(Of String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ src.vb(14) : error BC36716: Visual Basic 9.0 does not support auto-implemented properties. <CLSCompliant(False), Obsolete("obsolete message!")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <AttrInThisAsmAttribute()> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Public Property Scen2() As String ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ src.vb(14) : error BC36716: Visual Basic 9.0 does not support implicit line continuation. <CLSCompliant(False), Obsolete("obsolete message!")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <AttrInThisAsmAttribute()> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Public Property Scen2() As String ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </text>, output) CleanupAllGeneratedFiles(src.Path) End Sub <Fact> Public Sub DiagnosticFormatting() Dim source = " Class C Sub Main() Goo(0) #ExternalSource(""c:\temp\a\1.vb"", 10) Goo(1) #End ExternalSource #ExternalSource(""C:\a\..\b.vb"", 20) Goo(2) #End ExternalSource #ExternalSource(""C:\a\../B.vb"", 30) Goo(3) #End ExternalSource #ExternalSource(""../b.vb"", 40) Goo(4) #End ExternalSource #ExternalSource(""..\b.vb"", 50) Goo(5) #End ExternalSource #ExternalSource(""C:\X.vb"", 60) Goo(6) #End ExternalSource #ExternalSource(""C:\x.vb"", 70) Goo(7) #End ExternalSource #ExternalSource("" "", 90) Goo(9) #End ExternalSource #ExternalSource(""C:\*.vb"", 100) Goo(10) #End ExternalSource #ExternalSource("""", 110) Goo(11) #End ExternalSource Goo(12) #ExternalSource(""***"", 140) Goo(14) #End ExternalSource End Sub End Class " Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb").WriteAllText(source) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/preferreduilang:en", "/t:library", "a.vb"}) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) ' with /fullpaths off Dim expected = file.Path & "(4) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(0) ~~~ c:\temp\a\1.vb(10) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(1) ~~~ C:\b.vb(20) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(2) ~~~ C:\B.vb(30) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(3) ~~~ " & Path.GetFullPath(Path.Combine(dir.Path, "..\b.vb")) & "(40) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(4) ~~~ " & Path.GetFullPath(Path.Combine(dir.Path, "..\b.vb")) & "(50) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(5) ~~~ C:\X.vb(60) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(6) ~~~ C:\x.vb(70) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(7) ~~~ (90) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(9) ~~~ C:\*.vb(100) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(10) ~~~ (110) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(11) ~~~ " & file.Path & "(35) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(12) ~~~ ***(140) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(14) ~~~ " AssertOutput(expected.Replace(vbCrLf, vbLf), outWriter.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub ParseFeatures() Dim args = DefaultParse({"/features:Test", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("Test", args.ParseOptions.Features.Single().Key) args = DefaultParse({"/features:Test", "a.vb", "/Features:Experiment"}, _baseDirectory) args.Errors.Verify() Assert.Equal(2, args.ParseOptions.Features.Count) Assert.True(args.ParseOptions.Features.ContainsKey("Test")) Assert.True(args.ParseOptions.Features.ContainsKey("Experiment")) args = DefaultParse({"/features:Test=false,Key=value", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.ParseOptions.Features.SetEquals(New Dictionary(Of String, String) From {{"Test", "false"}, {"Key", "value"}})) ' We don't do any rigorous validation of /features arguments... args = DefaultParse({"/features", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Empty(args.ParseOptions.Features) args = DefaultParse({"/features:Test,", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.ParseOptions.Features.SetEquals(New Dictionary(Of String, String) From {{"Test", "true"}})) End Sub <Fact> Public Sub ParseAdditionalFile() Dim args = DefaultParse({"/additionalfile:web.config", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles.Single().Path) args = DefaultParse({"/additionalfile:web.config", "a.vb", "/additionalfile:app.manifest"}, _baseDirectory) args.Errors.Verify() Assert.Equal(2, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles(0).Path) Assert.Equal(Path.Combine(_baseDirectory, "app.manifest"), args.AdditionalFiles(1).Path) args = DefaultParse({"/additionalfile:web.config", "a.vb", "/additionalfile:web.config"}, _baseDirectory) args.Errors.Verify() Assert.Equal(2, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles(0).Path) Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles(1).Path) args = DefaultParse({"/additionalfile:..\web.config", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(Path.Combine(_baseDirectory, "..\web.config"), args.AdditionalFiles.Single().Path) Dim baseDir = Temp.CreateDirectory() baseDir.CreateFile("web1.config") baseDir.CreateFile("web2.config") baseDir.CreateFile("web3.config") args = DefaultParse({"/additionalfile:web*.config", "a.vb"}, baseDir.Path) args.Errors.Verify() Assert.Equal(3, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(baseDir.Path, "web1.config"), args.AdditionalFiles(0).Path) Assert.Equal(Path.Combine(baseDir.Path, "web2.config"), args.AdditionalFiles(1).Path) Assert.Equal(Path.Combine(baseDir.Path, "web3.config"), args.AdditionalFiles(2).Path) args = DefaultParse({"/additionalfile:web.config;app.manifest", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(2, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles(0).Path) Assert.Equal(Path.Combine(_baseDirectory, "app.manifest"), args.AdditionalFiles(1).Path) args = DefaultParse({"/additionalfile:web.config,app.manifest", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(2, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles(0).Path) Assert.Equal(Path.Combine(_baseDirectory, "app.manifest"), args.AdditionalFiles(1).Path) args = DefaultParse({"/additionalfile:""web.config,app.manifest""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(1, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config,app.manifest"), args.AdditionalFiles(0).Path) args = DefaultParse({"/additionalfile:\""web.config,app.manifest\""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(1, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config,app.manifest"), args.AdditionalFiles(0).Path) args = DefaultParse({"/additionalfile:\""""web.config,app.manifest""\""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(2, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles(0).Path) Assert.Equal(Path.Combine(_baseDirectory, "app.manifest"), args.AdditionalFiles(1).Path) args = DefaultParse({"/additionalfile:web.config:app.manifest", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(1, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config:app.manifest"), args.AdditionalFiles(0).Path) args = DefaultParse({"/additionalfile", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("additionalfile", ":<file_list>")) Assert.Equal(0, args.AdditionalFiles.Length) args = DefaultParse({"/additionalfile:", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("additionalfile", ":<file_list>")) Assert.Equal(0, args.AdditionalFiles.Length) End Sub <Fact> Public Sub ParseEditorConfig() Dim args = DefaultParse({"/analyzerconfig:.editorconfig", "a.vb"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig"), args.AnalyzerConfigPaths.Single()) args = DefaultParse({"/analyzerconfig:.editorconfig", "a.vb", "/analyzerconfig:subdir\.editorconfig"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(2, args.AnalyzerConfigPaths.Length) Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig"), args.AnalyzerConfigPaths(0)) Assert.Equal(Path.Combine(_baseDirectory, "subdir\.editorconfig"), args.AnalyzerConfigPaths(1)) args = DefaultParse({"/analyzerconfig:.editorconfig", "a.vb", "/analyzerconfig:.editorconfig"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(2, args.AnalyzerConfigPaths.Length) Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig"), args.AnalyzerConfigPaths(0)) Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig"), args.AnalyzerConfigPaths(1)) args = DefaultParse({"/analyzerconfig:..\.editorconfig", "a.vb"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(Path.Combine(_baseDirectory, "..\.editorconfig"), args.AnalyzerConfigPaths.Single()) args = DefaultParse({"/analyzerconfig:.editorconfig;subdir\.editorconfig", "a.vb"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(2, args.AnalyzerConfigPaths.Length) Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig"), args.AnalyzerConfigPaths(0)) Assert.Equal(Path.Combine(_baseDirectory, "subdir\.editorconfig"), args.AnalyzerConfigPaths(1)) args = DefaultParse({"/analyzerconfig:.editorconfig,subdir\.editorconfig", "a.vb"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(2, args.AnalyzerConfigPaths.Length) Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig"), args.AnalyzerConfigPaths(0)) Assert.Equal(Path.Combine(_baseDirectory, "subdir\.editorconfig"), args.AnalyzerConfigPaths(1)) args = DefaultParse({"/analyzerconfig:.editorconfig:.editorconfig", "a.vb"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(1, args.AnalyzerConfigPaths.Length) Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig:.editorconfig"), args.AnalyzerConfigPaths(0)) args = DefaultParse({"/analyzerconfig", "a.vb"}, _baseDirectory) args.Errors.AssertTheseDiagnostics( <errors><![CDATA[ BC2006: option 'analyzerconfig' requires ':<file_list>' ]]> </errors>) Assert.Equal(0, args.AnalyzerConfigPaths.Length) args = DefaultParse({"/analyzerconfig:", "a.vb"}, _baseDirectory) args.Errors.AssertTheseDiagnostics( <errors><![CDATA[ BC2006: option 'analyzerconfig' requires ':<file_list>']]> </errors>) Assert.Equal(0, args.AnalyzerConfigPaths.Length) End Sub Private Shared Sub Verify(actual As IEnumerable(Of Diagnostic), ParamArray expected As DiagnosticDescription()) actual.Verify(expected) End Sub Private Const s_logoLine1 As String = "Microsoft (R) Visual Basic Compiler version" Private Const s_logoLine2 As String = "Copyright (C) Microsoft Corporation. All rights reserved." Private Shared Function OccurrenceCount(source As String, word As String) As Integer Dim n = 0 Dim index = source.IndexOf(word, StringComparison.Ordinal) While (index >= 0) n += 1 index = source.IndexOf(word, index + word.Length, StringComparison.Ordinal) End While Return n End Function Private Shared Function VerifyOutput(sourceDir As TempDirectory, sourceFile As TempFile, Optional includeCurrentAssemblyAsAnalyzerReference As Boolean = True, Optional additionalFlags As String() = Nothing, Optional expectedInfoCount As Integer = 0, Optional expectedWarningCount As Integer = 0, Optional expectedErrorCount As Integer = 0, Optional errorlog As Boolean = False, Optional analyzers As ImmutableArray(Of DiagnosticAnalyzer) = Nothing) As String Dim args = { "/nologo", "/preferreduilang:en", "/t:library", sourceFile.Path } If includeCurrentAssemblyAsAnalyzerReference Then args = args.Append("/a:" + Assembly.GetExecutingAssembly().Location) End If If errorlog Then args = args.Append("/errorlog:errorlog") End If If additionalFlags IsNot Nothing Then args = args.Append(additionalFlags) End If Dim vbc = New MockVisualBasicCompiler(Nothing, sourceDir.Path, args, analyzers) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = vbc.Run(outWriter, Nothing) Dim output = outWriter.ToString() Dim expectedExitCode = If(expectedErrorCount > 0, 1, 0) Assert.True(expectedExitCode = exitCode, String.Format("Expected exit code to be '{0}' was '{1}'.{2}Output:{3}{4}", expectedExitCode, exitCode, Environment.NewLine, Environment.NewLine, output)) Assert.DoesNotContain(" : hidden", output, StringComparison.Ordinal) If expectedInfoCount = 0 Then Assert.DoesNotContain(" : info", output, StringComparison.Ordinal) Else ' Info diagnostics are only logged with /errorlog. Assert.True(errorlog) Assert.Equal(expectedInfoCount, OccurrenceCount(output, " : info")) End If If expectedWarningCount = 0 Then Assert.DoesNotContain(" : warning", output, StringComparison.Ordinal) Else Assert.Equal(expectedWarningCount, OccurrenceCount(output, " : warning")) End If If expectedErrorCount = 0 Then Assert.DoesNotContain(" : error", output, StringComparison.Ordinal) Else Assert.Equal(expectedErrorCount, OccurrenceCount(output, " : error")) End If Return output End Function <WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")> <Fact> Public Sub NoWarnAndWarnAsError_AnalyzerDriverWarnings() ' This assembly has an abstract MockAbstractDiagnosticAnalyzer type which should cause ' compiler warning BC42376 to be produced when compilations created in this test try to load it. Dim source = "Imports System" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim output = VerifyOutput(dir, file, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that compiler warning BC42376 can be suppressed via /nowarn. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn"}) ' TEST: Verify that compiler warning BC42376 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:BC42376"}) ' TEST: Verify that compiler warning BC42376 can be promoted to an error via /warnaserror+. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+"}, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' TEST: Verify that compiler warning BC42376 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:42376"}, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")> <WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")> <Fact> Public Sub NoWarnAndWarnAsError_HiddenDiagnostic() ' This assembly has a HiddenDiagnosticAnalyzer type which should produce custom hidden ' diagnostics for #ExternalSource directives present in the compilations created in this test. Dim source = "Imports System #ExternalSource (""file"", 123) #End ExternalSource" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim output = VerifyOutput(dir, file, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn"}) ' TEST: Verify that /nowarn: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /warnaserror+ has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/nowarn:42376"}) ' TEST: Verify that /warnaserror- has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /warnaserror: promotes custom hidden diagnostic Hidden01 to an error. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:hidden01"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify that /warnaserror-: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:Hidden01", "/nowarn:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:hidden01", "/warnaserror:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Hidden01", "/nowarn:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:hidden01", "/warnaserror-:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn doesn't override /warnaserror: in the case of custom hidden diagnostics. ' Although the compiler normally suppresses printing of hidden diagnostics in the compiler output, they are never really suppressed ' because in the IDE features that rely on hidden diagnostics to display light bulb need to continue to work even when users have global ' suppression (/nowarn) specified in their project. In other words, /nowarn flag is a no-op for hidden diagnostics. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/warnaserror:Hidden01"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify /nowarn doesn't override /warnaserror: in the case of custom hidden diagnostics. ' Although the compiler normally suppresses printing of hidden diagnostics in the compiler output, they are never really suppressed ' because in the IDE features that rely on hidden diagnostics to display light bulb need to continue to work even when users have global ' suppression (/nowarn) specified in their project. In other words, /nowarn flag is a no-op for hidden diagnostics. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:HIDDen01", "/nowarn"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify /nowarn and /warnaserror-: have no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Hidden01", "/nowarn"}) ' TEST: Verify /nowarn and /warnaserror-: have no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/warnaserror-:Hidden01"}) ' TEST: Sanity test for /nowarn and /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/nowarn:Hidden01"}) ' TEST: Sanity test for /nowarn and /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:Hidden01", "/nowarn"}) ' TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:Hidden01", "/warnaserror-:hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Hidden01", "/warnaserror+:hidden01"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/warnaserror+:hidden01"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:hiddEn01", "/warnaserror+", "/nowarn:42376"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:HiDden01", "/warnaserror-"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/warnaserror-:Hidden01", "/nowarn:42376"}) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/warnaserror-:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Hidden01", "/warnaserror-"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:HiDden01", "/warnaserror+", "/nowarn:42376"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/warnaserror+:HiDden01", "/nowarn:42376"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")> <WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")> <WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")> <CombinatorialData, Theory> Public Sub NoWarnAndWarnAsError_InfoDiagnostic(errorlog As Boolean) ' NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. ' This assembly has an InfoDiagnosticAnalyzer type which should produce custom info ' diagnostics for the #Enable directives present in the compilations created in this test. Dim source = "Imports System #Enable Warning" Dim name = "a.vb" Dim output = GetOutput(name, source, expectedWarningCount:=1, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that custom info diagnostic Info01 can be suppressed via /nowarn. output = GetOutput(name, source, additionalFlags:={"/nowarn"}, errorlog:=errorlog) ' TEST: Verify that custom info diagnostic Info01 can be individually suppressed via /nowarn:. output = GetOutput(name, source, additionalFlags:={"/nowarn:Info01"}, expectedWarningCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that custom info diagnostic Info01 can never be promoted to an error via /warnaserror+. output = GetOutput(name, source, additionalFlags:={"/warnaserror+", "/nowarn:42376"}, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that custom info diagnostic Info01 is still reported as an info when /warnaserror- is used. output = GetOutput(name, source, additionalFlags:={"/warnaserror-"}, expectedWarningCount:=1, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that custom info diagnostic Info01 can be individually promoted to an error via /warnaserror:. output = GetOutput(name, source, additionalFlags:={"/warnaserror:info01"}, expectedWarningCount:=1, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) ' TEST: Verify that custom info diagnostic Info01 is still reported as an info when passed to /warnaserror-:. output = GetOutput(name, source, additionalFlags:={"/warnaserror-:info01"}, expectedWarningCount:=1, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify /nowarn: overrides /warnaserror:. output = GetOutput(name, source, additionalFlags:={"/warnaserror:Info01", "/nowarn:info01"}, expectedWarningCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror:. output = GetOutput(name, source, additionalFlags:={"/nowarn:INFO01", "/warnaserror:Info01"}, expectedWarningCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror-:. output = GetOutput(name, source, additionalFlags:={"/warnaserror-:Info01", "/nowarn:info01"}, expectedWarningCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror-:. output = GetOutput(name, source, additionalFlags:={"/nowarn:INFO01", "/warnaserror-:Info01"}, expectedWarningCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn overrides /warnaserror:. output = GetOutput(name, source, additionalFlags:={"/nowarn", "/warnaserror:Info01"}, errorlog:=errorlog) ' TEST: Verify /nowarn overrides /warnaserror:. output = GetOutput(name, source, additionalFlags:={"/warnaserror:Info01", "/nowarn"}, errorlog:=errorlog) ' TEST: Verify /nowarn overrides /warnaserror-:. output = GetOutput(name, source, additionalFlags:={"/nowarn", "/warnaserror-:Info01"}, errorlog:=errorlog) ' TEST: Verify /nowarn overrides /warnaserror-:. output = GetOutput(name, source, additionalFlags:={"/warnaserror-:Info01", "/nowarn"}, errorlog:=errorlog) ' TEST: Sanity test for /nowarn and /nowarn:. output = GetOutput(name, source, additionalFlags:={"/nowarn", "/nowarn:Info01"}, errorlog:=errorlog) ' TEST: Sanity test for /nowarn and /nowarn:. output = GetOutput(name, source, additionalFlags:={"/nowarn:Info01", "/nowarn"}, errorlog:=errorlog) ' TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags:={"/warnaserror+:Info01", "/warnaserror-:info01"}, expectedWarningCount:=1, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags:={"/warnaserror-:Info01", "/warnaserror+:INfo01"}, expectedWarningCount:=1, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror-", "/warnaserror+:info01"}, expectedWarningCount:=1, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror+:InFo01", "/warnaserror+", "/nowarn:42376"}, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror+:InfO01", "/warnaserror-"}, expectedWarningCount:=1, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror+", "/warnaserror-:INfo01", "/nowarn:42376"}, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror-", "/warnaserror-:INfo01"}, expectedWarningCount:=1, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror-:Info01", "/warnaserror-"}, expectedWarningCount:=1, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror+", "/warnaserror+:Info01", "/nowarn:42376"}, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror+:InFO01", "/warnaserror+", "/nowarn:42376"}, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End Sub Private Function GetOutput(name As String, source As String, Optional includeCurrentAssemblyAsAnalyzerReference As Boolean = True, Optional additionalFlags As String() = Nothing, Optional expectedInfoCount As Integer = 0, Optional expectedWarningCount As Integer = 0, Optional expectedErrorCount As Integer = 0, Optional errorlog As Boolean = False) As String Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(name) file.WriteAllText(source) Dim output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference, additionalFlags, expectedInfoCount, expectedWarningCount, expectedErrorCount, errorlog) CleanupAllGeneratedFiles(file.Path) Return output End Function <WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")> <WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")> <WorkItem(998069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998069")> <WorkItem(998724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998724")> <Fact> Public Sub NoWarnAndWarnAsError_WarningDiagnostic() ' This assembly has a WarningDiagnosticAnalyzer type which should produce custom warning ' diagnostics for source types present in the compilations created in this test. Dim source = "Imports System Module Module1 Sub Main Dim x as Integer End Sub End Module" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim output = VerifyOutput(dir, file, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that compiler warning BC42024 as well as custom warning diagnostics Warning01 and Warning03 can be suppressed via /nowarn. ' This doesn't work for BC42376 currently (Bug 899050). output = VerifyOutput(dir, file, additionalFlags:={"/nowarn"}) ' TEST: Verify that compiler warning BC42024 as well as custom warning diagnostics Warning01 and Warning03 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that compiler warning BC42024 as well as custom warning diagnostics Warning01 and Warning03 can be promoted to errors via /warnaserror. ' Promoting compiler warning BC42024 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror"}, expectedWarningCount:=0, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' TEST: Verify that compiler warning BC42024 as well as custom warning diagnostics Warning01 and Warning03 can be promoted to errors via /warnaserror+. ' This doesn't work correctly currently - promoting compiler warning BC42024 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+"}, expectedWarningCount:=0, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /warnaserror- keeps compiler warning BC42024 as well as custom warning diagnostics Warning01 and Warning03 as warnings. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that custom warning diagnostics Warning01 and Warning03 can be individually promoted to errors via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:warning01,Something,warning03"}, expectedWarningCount:=2, expectedErrorCount:=2) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that compiler warning BC42024 can be individually promoted to an error via /warnaserror+:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:bc42024"}, expectedWarningCount:=3, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : error BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that custom warning diagnostics Warning01 and Warning03 as well as compiler warning BC42024 can be individually promoted to errors via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1, expectedErrorCount:=3) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : error BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that last flag on command line wins between /nowarn and /warnaserror. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror", "/nowarn"}) ' TEST: Verify that last flag on command line wins between /nowarn and /warnaserror+. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/warnaserror+"}, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/warnaserror-"}) ' TEST: Verify that /nowarn overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/nowarn"}) ' TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:Something,042024,Warning01,Warning03", "/nowarn:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000", "/warnaserror:Something,042024,Warning01,Warning03"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Something,042024,Warning01,Warning03", "/nowarn:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000", "/warnaserror-:Something,042024,Warning01,Warning03"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/nowarn:warning01,Warning03,bc42024,58000,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000,42376", "/warnaserror"}) ' TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/nowarn:warning01,Warning03,bc42024,58000,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000,42376", "/warnaserror-"}) ' TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:warning01,Warning03,bc42024,58000", "/nowarn:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000", "/warnaserror-:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/warnaserror:Something,042024,Warning01,Warning03,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000,42376", "/warnaserror"}) ' TEST: Verify that /nowarn overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Something,042024,Warning01,Warning03,42376", "/nowarn"}) ' TEST: Verify that /nowarn overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/warnaserror-:Something,042024,Warning01,Warning03,42376"}) ' TEST: Sanity test for /nowarn and /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/nowarn:Something,042024,Warning01,Warning03,42376"}) ' TEST: Sanity test for /nowarn: and /nowarn. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:Something,042024,Warning01,Warning03,42376", "/nowarn"}) ' TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/warnaserror+"}, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' Note: Old native compiler behaved strangely for the below case. ' When /warnaserror+ and /warnaserror- appeared on the same command line, native compiler would allow /warnaserror+ to win always ' regardless of order. However when /warnaserror+:xyz and /warnaserror-:xyz appeared on the same command line, native compiler ' would allow the flag that appeared last on the command line to win. Roslyn compiler allows the last flag that appears on the ' command line to win in both cases. This is not a breaking change since at worst this only makes a case that used to be an error ' in the native compiler to be a warning in Roslyn. ' TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/warnaserror-"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:warning01,Warning03", "/warnaserror+:Warning01,Warning03"}, expectedWarningCount:=2, expectedErrorCount:=2) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:Warning01,Warning03", "/warnaserror-:warning01,Warning03"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:warning01,Warning03,bc42024,58000,42376", "/warnaserror+"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:warning01,Warning03,58000", "/warnaserror-"}, expectedWarningCount:=2, expectedErrorCount:=2) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/warnaserror+:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1, expectedErrorCount:=3) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : error BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/warnaserror-:warning01,Warning03,bc42024,58000,42376"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/warnaserror+:warning01,Warning03,bc42024,58000,42376"}, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:warning01,Warning03,bc42024,58000,42376", "/warnaserror"}, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/warnaserror-:warning01,Warning03,bc42024,58000,42376"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:warning01,Warning03,bc42024,58000,42376", "/warnaserror-"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")> <WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")> <Fact> Public Sub NoWarnAndWarnAsError_ErrorDiagnostic() ' This assembly has an ErrorDiagnosticAnalyzer type which should produce custom error ' diagnostics for #Disable directives present in the compilations created in this test. Dim source = "Imports System #Disable Warning" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' TEST: Verify that custom error diagnostic Error01 can't be suppressed via /nowarn. Dim output = VerifyOutput(dir, file, additionalFlags:={"/nowarn"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) ' TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:Error01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:ERROR01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/nowarn:ERROR01,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:ERROR01,42376", "/warnaserror"}) ' TEST: Verify that /nowarn: overrides /warnaserror+:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:Error01,42376", "/nowarn:ERROR01,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:ERROR01,42376", "/warnaserror:Error01,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/nowarn:ERROR01,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:ERROR01,42376", "/warnaserror-"}) ' TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Error01,42376", "/nowarn:ERROR01,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:ERROR01,42376", "/warnaserror-:Error01,42376"}) ' TEST: Verify that nothing bad happens when using /warnaserror[+/-] when custom error diagnostic Error01 is present. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror", "/nowarn:42376"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/nowarn:42376"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) ' TEST: Verify that nothing bad happens if someone passes custom error diagnostic Error01 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:Error01"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:ERROR01"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Error01"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")> <Fact> Public Sub NoWarnAndWarnAsError_CompilerErrorDiagnostic() Dim source = "Imports System Module Module1 Sub Main Dim x as Integer = New Exception() End Sub End Module" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) ' TEST: Verify that compiler error BC30311 can't be suppressed via /nowarn. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) ' TEST: Verify that compiler error BC30311 can't be suppressed via /nowarn:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:BC30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:bc30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) ' TEST: Verify that nothing bad happens when using /warnaserror[+/-] when compiler error BC30311 is present. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror+"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror-"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) ' TEST: Verify that nothing bad happens if someone passes BC30311 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror:30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror+:BC30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror+:bc30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror-:30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror-:BC30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror-:bc30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <Fact, WorkItem(1091972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091972"), WorkItem(444, "CodePlex")> Public Sub Bug1091972() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C Shared Sub Main() Dim textStreamReader = New System.IO.StreamReader(GetType(C).Assembly.GetManifestResourceStream("doc.xml")) System.Console.WriteLine(textStreamReader.ReadToEnd()) End Sub End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /doc:doc.xml /out:out.exe /resource:doc.xml {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml"))) Dim expected = <text> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> out </name> </assembly> <members> <member name="T:C"> <summary>ABC...XYZ</summary> </member> </members> </doc> ]]> </text> Using reader As New StreamReader(Path.Combine(dir.ToString(), "doc.xml")) Dim content = reader.ReadToEnd() AssertOutput(expected, content) End Using output = ProcessUtilities.RunAndGetOutput(Path.Combine(dir.ToString(), "out.exe"), startFolder:=dir.ToString()) AssertOutput(expected, output) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=0, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Info, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+:Test001", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Default, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralWarnAsErrorMinusResetsRules() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+", "/WarnAsError-", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Default, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Warn, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificWarnAsErrorMinusResetsRules() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+", "/WarnAsError-:Test001", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Warn, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+:Test002", "/WarnAsError-:Test002", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Default, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=2, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Warn, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) Assert.Equal(expected:=ReportDiagnostic.Default, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test002")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_LastGeneralWarnAsErrorTrumpsNoWarn() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/NoWarn", "/WarnAsError+", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralNoWarnTrumpsGeneralWarnAsErrorMinus() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+", "/NoWarn", "/WarnAsError-", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Warn, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralNoWarnTurnsOffAllButErrors() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Error"" /> <Rule Id=""Test002"" Action=""Warning"" /> <Rule Id=""Test003"" Action=""Info"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/NoWarn", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=3, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test002")) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test003")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificNoWarnAlwaysWins() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/NoWarn:Test001", "/WarnAsError+", "/WarnAsError-:Test001", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact> Public Sub ReportAnalyzer() Dim args1 = DefaultParse({"/reportanalyzer", "a.vb"}, _baseDirectory) Assert.True(args1.ReportAnalyzer) Dim args2 = DefaultParse({"", "a.vb"}, _baseDirectory) Assert.False(args2.ReportAnalyzer) End Sub <Fact> Public Sub ReportAnalyzerOutput() Dim source As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, source}) Dim outWriter = New StringWriter() Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) Dim output = outWriter.ToString() Assert.Contains(New WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal) Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal) CleanupAllGeneratedFiles(source) End Sub <Fact> <WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")> Public Sub SkipAnalyzersParse() Dim ParsedArgs = DefaultParse({"a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.False(ParsedArgs.SkipAnalyzers) ParsedArgs = DefaultParse({"/skipanalyzers+", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.True(ParsedArgs.SkipAnalyzers) ParsedArgs = DefaultParse({"/skipanalyzers", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.True(ParsedArgs.SkipAnalyzers) ParsedArgs = DefaultParse({"/SKIPANALYZERS+", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.True(ParsedArgs.SkipAnalyzers) ParsedArgs = DefaultParse({"/skipanalyzers-", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.False(ParsedArgs.SkipAnalyzers) ParsedArgs = DefaultParse({"/skipanalyzers-", "/skipanalyzers+", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.True(ParsedArgs.SkipAnalyzers) ParsedArgs = DefaultParse({"/skipanalyzers", "/skipanalyzers-", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.False(ParsedArgs.SkipAnalyzers) End Sub <Theory, CombinatorialData> <WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")> Public Sub SkipAnalyzersSemantics(skipAnalyzers As Boolean) Dim source As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim skipAnalyzersFlag = "/skipanalyzers" + If(skipAnalyzers, "+", "-") Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {skipAnalyzersFlag, "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, source}) Dim outWriter = New StringWriter() Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) Dim output = outWriter.ToString() If skipAnalyzers Then Assert.DoesNotContain(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal) Assert.DoesNotContain(New WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal) Else Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal) Assert.Contains(New WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal) End If CleanupAllGeneratedFiles(source) End Sub <Fact> <WorkItem(1759, "https://github.com/dotnet/roslyn/issues/1759")> Public Sub AnalyzerDiagnosticThrowsInGetMessage() Dim source As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", source}, analyzer:=New AnalyzerThatThrowsInGetMessage) Dim outWriter = New StringWriter() Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) Dim output = outWriter.ToString() ' Verify that the diagnostic reported by AnalyzerThatThrowsInGetMessage is reported, though it doesn't have the message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal) ' Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal) Assert.Contains(NameOf(NotImplementedException), output, StringComparison.Ordinal) CleanupAllGeneratedFiles(source) End Sub <Fact> <WorkItem(3707, "https://github.com/dotnet/roslyn/issues/3707")> Public Sub AnalyzerExceptionDiagnosticCanBeConfigured() Dim source As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", $"/warnaserror:{AnalyzerExecutor.AnalyzerExceptionDiagnosticId}", source}, analyzer:=New AnalyzerThatThrowsInGetMessage) Dim outWriter = New StringWriter() Dim exitCode = vbc.Run(outWriter, Nothing) Assert.NotEqual(0, exitCode) Dim output = outWriter.ToString() ' Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal) Assert.Contains(NameOf(NotImplementedException), output, StringComparison.Ordinal) CleanupAllGeneratedFiles(source) End Sub <Fact> <WorkItem(4589, "https://github.com/dotnet/roslyn/issues/4589")> Public Sub AnalyzerReportsMisformattedDiagnostic() Dim source As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", source}, analyzer:=New AnalyzerReportingMisformattedDiagnostic) Dim outWriter = New StringWriter() Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) Dim output = outWriter.ToString() ' Verify that the diagnostic reported by AnalyzerReportingMisformattedDiagnostic is reported with the message format string, instead of the formatted message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal) Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.MessageFormat.ToString(CultureInfo.InvariantCulture), output, StringComparison.Ordinal) CleanupAllGeneratedFiles(source) End Sub <Fact> Public Sub AdditionalFileDiagnostics() Dim dir = Temp.CreateDirectory() Dim source = dir.CreateFile("a.vb").WriteAllText(<text> Class C End Class </text>.Value).Path Dim additionalFile = dir.CreateFile("AdditionalFile.txt").WriteAllText(<text> Additional File Line 1! Additional File Line 2! </text>.Value).Path Dim nonCompilerInputFile = dir.CreateFile("DummyFile.txt").WriteAllText(<text> Dummy File Line 1! </text>.Value).Path Dim analyzer = New AdditionalFileDiagnosticAnalyzer(nonCompilerInputFile) Dim arguments = {"/nologo", "/preferreduilang:en", "/vbruntime", "/t:library", "/additionalfile:" & additionalFile, ' Valid additional text file "/additionalfile:" & Assembly.GetExecutingAssembly.Location, ' Non-text file specified as an additional text file source} Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, arguments, analyzer) Dim outWriter = New StringWriter() Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) Dim output = outWriter.ToString() AssertOutput( String.Format(<text> AdditionalFile.txt(1) : warning AdditionalFileDiagnostic: Additional File Diagnostic: AdditionalFile Additional File Line 1! ~~~~~~~~~~ vbc : warning AdditionalFileDiagnostic: Additional File Diagnostic: {0} vbc : warning AdditionalFileDiagnostic: Additional File Diagnostic: AdditionalFile vbc : warning AdditionalFileDiagnostic: Additional File Diagnostic: DummyFile vbc : warning AdditionalFileDiagnostic: Additional File Diagnostic: NonExistentPath vbc : error BC2015: the file '{1}' is not a text file </text>.Value.ToString(), IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly.Location), Assembly.GetExecutingAssembly.Location), output, fileName:="AdditionalFile.txt") CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(additionalFile) CleanupAllGeneratedFiles(nonCompilerInputFile) End Sub <Fact, WorkItem(1093063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1093063")> Public Sub VerifyDiagnosticSeverityNotLocalized() Dim source = <![CDATA[ Class A End Class ]]> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/target:exe", fileName}) vbc.Run(output, Nothing) ' If "error" was localized, below assert will fail on PLOC builds. The output would be something like: "!pTCvB!vbc : !FLxft!error 表! BC30420:" Assert.Contains("error BC30420:", output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <ConditionalFact(GetType(WindowsOnly))> Public Sub SourceFile_BadPath() Dim args = DefaultParse({"e:c:\test\test.cs", "/t:library"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("e:c:\test\test.cs").WithLocation(1, 1)) End Sub <ConditionalFact(GetType(WindowsOnly))> Public Sub FilePaths() Dim args = FullParse("\\unc\path\a.vb b.vb c:\path\c.vb", "e:\temp") Assert.Equal( New String() {"\\unc\path\a.vb", "e:\temp\b.vb", "c:\path\c.vb"}, args.SourceFiles.Select(Function(x) x.Path)) args = FullParse("\\unc\path\a.vb ""b.vb"" c:\path\c.vb", "e:\temp") Assert.Equal( New String() {"\\unc\path\a.vb", "e:\temp\b.vb", "c:\path\c.vb"}, args.SourceFiles.Select(Function(x) x.Path)) args = FullParse("""b"".vb""", "e:\temp") Assert.Equal( New String() {"e:\temp\b.vb"}, args.SourceFiles.Select(Function(x) x.Path)) End Sub <ConditionalFact(GetType(WindowsOnly))> Public Sub ReferencePathsEx() Dim args = FullParse("/nostdlib /vbruntime- /noconfig /r:a.dll,b.dll test.vb", "e:\temp") Assert.Equal( New String() {"a.dll", "b.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) args = FullParse("/nostdlib /vbruntime- /noconfig /r:""a.dll,b.dll"" test.vb", "e:\temp") Assert.Equal( New String() {"a.dll,b.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) args = FullParse("/nostdlib /vbruntime- /noconfig /r:""lib, ex\a.dll"",b.dll test.vb", "e:\temp") Assert.Equal( New String() {"lib, ex\a.dll", "b.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) args = FullParse("/nostdlib /vbruntime- /noconfig /r:""lib, ex\a.dll"" test.vb", "e:\temp") Assert.Equal( New String() {"lib, ex\a.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) End Sub <ConditionalFact(GetType(WindowsOnly))> Public Sub ParseAssemblyReferences() Dim parseCore = Sub(value As String, paths As String()) Dim list As New List(Of Diagnostic) Dim references = VisualBasicCommandLineParser.ParseAssemblyReferences("", value, list, embedInteropTypes:=False) Assert.Equal(0, list.Count) Assert.Equal(paths, references.Select(Function(r) r.Reference)) End Sub parseCore("""a.dll""", New String() {"a.dll"}) parseCore("a,b", New String() {"a", "b"}) parseCore("""a,b""", New String() {"a,b"}) ' This is an intentional deviation from the native compiler. BCL docs on MSDN, MSBuild and the C# compiler ' treat a semicolon as a separator. VB compiler was the lone holdout here. Rather than deviate we decided ' to unify the behavior. parseCore("a;b", New String() {"a", "b"}) parseCore("""a;b""", New String() {"a;b"}) ' Note this case can only happen when it is the last option on the command line. When done ' in another position the command line splitting routine would continue parsing all the text ' after /r:"a as it resides in an unterminated quote. parseCore("""a", New String() {"a"}) parseCore("a""mid""b", New String() {"amidb"}) End Sub <Fact> Public Sub PublicSign() Dim args As VisualBasicCommandLineArguments Dim baseDir = "c:\test" Dim parse = Function(x As String) FullParse(x, baseDir) args = parse("/publicsign a.exe") Assert.True(args.CompilationOptions.PublicSign) args = parse("/publicsign+ a.exe") Assert.True(args.CompilationOptions.PublicSign) args = parse("/publicsign- a.exe") Assert.False(args.CompilationOptions.PublicSign) args = parse("a.exe") Assert.False(args.CompilationOptions.PublicSign) End Sub <WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")> <Fact> Public Sub PublicSign_KeyFileRelativePath() Dim parsedArgs = FullParse("/publicsign /keyfile:test.snk a.cs", _baseDirectory) Assert.Equal(Path.Combine(_baseDirectory, "test.snk"), parsedArgs.CompilationOptions.CryptoKeyFile) parsedArgs.Errors.Verify() End Sub <WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> <Fact> Public Sub PublicSignWithEmptyKeyPath() Dim parsedArgs = FullParse("/publicsign /keyfile: a.cs", _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keyfile", ":<file>").WithLocation(1, 1)) End Sub <WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> <Fact> Public Sub PublicSignWithEmptyKeyPath2() Dim parsedArgs = FullParse("/publicsign /keyfile:"""" a.cs", _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keyfile", ":<file>").WithLocation(1, 1)) End Sub <ConditionalFact(GetType(WindowsOnly))> Public Sub CommandLineMisc() Dim args As VisualBasicCommandLineArguments Dim baseDir = "c:\test" Dim parse = Function(x As String) FullParse(x, baseDir) args = parse("/out:""a.exe""") Assert.Equal("a.exe", args.OutputFileName) args = parse("/out:""a-b.exe""") Assert.Equal("a-b.exe", args.OutputFileName) args = parse("/out:""a,b.exe""") Assert.Equal("a,b.exe", args.OutputFileName) ' The \ here causes " to be treated as a quote, not as an escaping construct args = parse("a\""b c""\d.cs") Assert.Equal( New String() {"c:\test\a""b", "c:\test\c\d.cs"}, args.SourceFiles.Select(Function(x) x.Path)) args = parse("a\\""b c""\d.cs") Assert.Equal( New String() {"c:\test\a\b c\d.cs"}, args.SourceFiles.Select(Function(x) x.Path)) args = parse("/nostdlib /vbruntime- /r:""a.dll"",""b.dll"" c.cs") Assert.Equal( New String() {"a.dll", "b.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) args = parse("/nostdlib /vbruntime- /r:""a-s.dll"",""b-s.dll"" c.cs") Assert.Equal( New String() {"a-s.dll", "b-s.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) args = parse("/nostdlib /vbruntime- /r:""a,s.dll"",""b,s.dll"" c.cs") Assert.Equal( New String() {"a,s.dll", "b,s.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) End Sub <WorkItem(7588, "https://github.com/dotnet/roslyn/issues/7588")> <Fact()> Public Sub Version() Dim folderName = Temp.CreateDirectory().ToString() Dim argss = { "/version", "a.cs /version /preferreduilang:en", "/version /nologo", "/version /help"} For Each args In argss Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, args, startFolder:=folderName) Assert.Equal(s_compilerVersion, output.Trim()) Next End Sub <Fact> Public Sub RefOut() Dim dir = Temp.CreateDirectory() Dim refDir = dir.CreateDirectory("ref") Dim src = dir.CreateFile("a.vb") src.WriteAllText(" Public Class C ''' <summary>Main method</summary> Public Shared Sub Main() System.Console.Write(""Hello"") End Sub ''' <summary>Private method</summary> Private Shared Sub PrivateMethod() System.Console.Write(""Private"") End Sub End Class") Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/define:_MYTYPE=""Empty"" ", "/nologo", "/out:a.exe", "/refout:ref/a.dll", "/doc:doc.xml", "/deterministic", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(0, exitCode) Dim exe = Path.Combine(dir.Path, "a.exe") Assert.True(File.Exists(exe)) MetadataReaderUtils.VerifyPEMetadata(exe, {"TypeDefinition:<Module>", "TypeDefinition:C"}, {"MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()", "MethodDefinition:Void C.PrivateMethod()"}, {"CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "STAThreadAttribute"} ) Dim doc = Path.Combine(dir.Path, "doc.xml") Assert.True(File.Exists(doc)) Dim content = File.ReadAllText(doc) Dim expectedDoc = "<?xml version=""1.0""?> <doc> <assembly> <name> a </name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""M:C.PrivateMethod""> <summary>Private method</summary> </member> </members> </doc>" Assert.Equal(expectedDoc, content.Trim()) Dim output = ProcessUtilities.RunAndGetOutput(exe, startFolder:=dir.Path) Assert.Equal("Hello", output.Trim()) Dim refDll = Path.Combine(refDir.Path, "a.dll") Assert.True(File.Exists(refDll)) ' The types and members that are included needs further refinement. ' See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, {"TypeDefinition:<Module>", "TypeDefinition:C"}, {"MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()"}, {"CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "STAThreadAttribute", "ReferenceAssemblyAttribute"} ) ' Clean up temp files CleanupAllGeneratedFiles(dir.Path) CleanupAllGeneratedFiles(refDir.Path) End Sub <Fact> Public Sub RefOutWithError() Dim dir = Temp.CreateDirectory() dir.CreateDirectory("ref") Dim src = dir.CreateFile("a.vb") src.WriteAllText( "Class C Public Shared Sub Main() Bad() End Sub End Class") Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/define:_MYTYPE=""Empty"" ", "/nologo", "/out:a.dll", "/refout:ref/a.dll", "/deterministic", "/preferreduilang:en", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(1, exitCode) Dim vb = Path.Combine(dir.Path, "a.vb") Dim dll = Path.Combine(dir.Path, "a.dll") Assert.False(File.Exists(dll)) Dim refDll = Path.Combine(dir.Path, Path.Combine("ref", "a.dll")) Assert.False(File.Exists(refDll)) Assert.Equal( $"{vb}(3) : error BC30451: 'Bad' is not declared. It may be inaccessible due to its protection level. Bad() ~~~", outWriter.ToString().Trim()) ' Clean up temp files CleanupAllGeneratedFiles(dir.Path) End Sub <Fact> Public Sub RefOnly() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( "Class C ''' <summary>Main method</summary> Public Shared Sub Main() Bad() End Sub ''' <summary>Field</summary> Private Dim field As Integer ''' <summary>Field</summary> Private Structure S ''' <summary>Struct Field</summary> Private Dim field As Integer End Structure End Class") Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/define:_MYTYPE=""Empty"" ", "/nologo", "/out:a.dll", "/refonly", "/debug", "/deterministic", "/doc:doc.xml", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(0, exitCode) Dim refDll = Path.Combine(dir.Path, "a.dll") Assert.True(File.Exists(refDll)) ' The types and members that are included needs further refinement. ' See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, {"TypeDefinition:<Module>", "TypeDefinition:C", "TypeDefinition:S"}, {"MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()"}, {"CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "STAThreadAttribute", "ReferenceAssemblyAttribute"} ) Dim pdb = Path.Combine(dir.Path, "a.pdb") Assert.False(File.Exists(pdb)) Dim doc = Path.Combine(dir.Path, "doc.xml") Assert.True(File.Exists(doc)) Dim content = File.ReadAllText(doc) Dim expectedDoc = "<?xml version=""1.0""?> <doc> <assembly> <name> a </name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""F:C.field""> <summary>Field</summary> </member> <member name=""T:C.S""> <summary>Field</summary> </member> <member name=""F:C.S.field""> <summary>Struct Field</summary> </member> </members> </doc>" Assert.Equal(expectedDoc, content.Trim()) ' Clean up temp files CleanupAllGeneratedFiles(dir.Path) End Sub <WorkItem(13681, "https://github.com/dotnet/roslyn/issues/13681")> <Theory()> <InlineData("/t:exe", "/out:goo.dll", "goo.dll", "goo.dll.exe")> 'Output with known but different extension <InlineData("/t:exe", "/out:goo.dLL", "goo.dLL", "goo.dLL.exe")> 'Output with known but different extension (different casing) <InlineData("/t:library", "/out:goo.exe", "goo.exe", "goo.exe.dll")> 'Output with known but different extension <InlineData("/t:library", "/out:goo.eXe", "goo.eXe", "goo.eXe.dll")> 'Output with known but different extension (different casing) <InlineData("/t:module", "/out:goo.dll", "goo.dll", "goo.dll.netmodule")> 'Output with known but different extension <InlineData("/t:winmdobj", "/out:goo.netmodule", "goo.netmodule", "goo.netmodule.winmdobj")> 'Output with known but different extension <InlineData("/t:exe", "/out:goo.netmodule", "goo.netmodule", "goo.netmodule.exe")> 'Output with known but different extension <InlineData("/t:library", "/out:goo.txt", "goo.txt.dll", "goo.dll")> 'Output with unknown extension (.txt) <InlineData("/t:exe", "/out:goo.md", "goo.md.exe", "goo.exe")> 'Output with unknown extension (.md) <InlineData("/t:exe", "/out:goo", "goo.exe", "goo")> 'Output without extension <InlineData("/t:library", "/out:goo", "goo.dll", "goo")> 'Output without extension <InlineData("/t:module", "/out:goo", "goo.netmodule", "goo")> 'Output without extension <InlineData("/t:winmdobj", "/out:goo", "goo.winmdobj", "goo")> 'Output without extension <InlineData("/t:exe", "/out:goo.exe", "goo.exe", "goo.exe.exe")> 'Output with correct extension (.exe) <InlineData("/t:library", "/out:goo.dll", "goo.dll", "goo.dll.dll")> 'Output with correct extension (.dll) <InlineData("/t:module", "/out:goo.netmodule", "goo.netmodule", "goo.netmodule.netmodule")> 'Output with correct extension (.netmodule) <InlineData("/t:module", "/out:goo.NetModule", "goo.NetModule", "goo.NetModule.netmodule")> 'Output with correct extension (.netmodule) (different casing) <InlineData("/t:winmdobj", "/out:goo.winmdobj", "goo.winmdobj", "goo.winmdobj.winmdobj")> 'Output with correct extension (.winmdobj) Public Sub OutputingFilesWithDifferentExtensions(targetArg As String, outArg As String, expectedFile As String, unexpectedFile As String) Dim source = <compilation> <file name="a.vb"> <![CDATA[ Module Program Sub Main(args As String()) End Sub End Module ]]> </file> </compilation> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim sourceFile = dir.CreateFile(fileName) sourceFile.WriteAllText(source.Value) Dim output As New StringWriter() Assert.Equal(0, New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, targetArg, outArg}).Run(output, Nothing)) Assert.True(File.Exists(Path.Combine(dir.Path, expectedFile)), "Expected to find: " & expectedFile) Assert.False(File.Exists(Path.Combine(dir.Path, unexpectedFile)), "Didn't expect to find: " & unexpectedFile) CleanupAllGeneratedFiles(sourceFile.Path) End Sub <Fact> Public Sub IOFailure_DisposeOutputFile() Dim srcPath = MakeTrivialExe(Temp.CreateDirectory().Path) Dim exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe") Dim vbc = New MockVisualBasicCompiler(_baseDirectory, {"/nologo", "/preferreduilang:en", $"/out:{exePath}", srcPath}) vbc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc:= Function(filePath, mode, access, share) If filePath = exePath Then Return New TestStream(backingStream:=New MemoryStream(), dispose:=Sub() Throw New IOException("Fake IOException")) End If Return File.Open(filePath, mode, access, share) End Function) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Assert.Equal(1, vbc.Run(outWriter)) Assert.Equal($"vbc : error BC2012: can't open '{exePath}' for writing: Fake IOException{Environment.NewLine}", outWriter.ToString()) End Sub <Fact> Public Sub IOFailure_DisposePdbFile() Dim srcPath = MakeTrivialExe(Temp.CreateDirectory().Path) Dim exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe") Dim pdbPath = Path.ChangeExtension(exePath, "pdb") Dim vbc = New MockVisualBasicCompiler(_baseDirectory, {"/nologo", "/preferreduilang:en", "/debug", $"/out:{exePath}", srcPath}) vbc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc:= Function(filePath, mode, access, share) If filePath = pdbPath Then Return New TestStream(backingStream:=New MemoryStream(), dispose:=Sub() Throw New IOException("Fake IOException")) End If Return File.Open(filePath, mode, access, share) End Function) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Assert.Equal(1, vbc.Run(outWriter)) Assert.Equal($"vbc : error BC2012: can't open '{pdbPath}' for writing: Fake IOException{Environment.NewLine}", outWriter.ToString()) End Sub <Fact> Public Sub IOFailure_DisposeXmlFile() Dim srcPath = MakeTrivialExe(Temp.CreateDirectory().Path) Dim xmlPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.xml") Dim vbc = New MockVisualBasicCompiler(_baseDirectory, {"/nologo", "/preferreduilang:en", $"/doc:{xmlPath}", srcPath}) vbc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc:= Function(filePath, mode, access, share) If filePath = xmlPath Then Return New TestStream(backingStream:=New MemoryStream(), dispose:=Sub() Throw New IOException("Fake IOException")) End If Return File.Open(filePath, mode, access, share) End Function) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Assert.Equal(1, vbc.Run(outWriter)) Assert.Equal($"vbc : error BC2012: can't open '{xmlPath}' for writing: Fake IOException{Environment.NewLine}", outWriter.ToString()) End Sub <Theory> <InlineData("portable")> <InlineData("full")> Public Sub IOFailure_DisposeSourceLinkFile(format As String) Dim srcPath = MakeTrivialExe(Temp.CreateDirectory().Path) Dim sourceLinkPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.json") Dim vbc = New MockVisualBasicCompiler(_baseDirectory, {"/nologo", "/preferreduilang:en", "/debug:" & format, $"/sourcelink:{sourceLinkPath}", srcPath}) vbc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc:= Function(filePath, mode, access, share) If filePath = sourceLinkPath Then Return New TestStream( backingStream:=New MemoryStream(Encoding.UTF8.GetBytes(" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } ")), dispose:=Sub() Throw New IOException("Fake IOException")) End If Return File.Open(filePath, mode, access, share) End Function) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Assert.Equal(1, vbc.Run(outWriter)) Assert.Equal($"vbc : error BC2012: can't open '{sourceLinkPath}' for writing: Fake IOException{Environment.NewLine}", outWriter.ToString()) End Sub <Fact> Public Sub CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics() Dim parsedArgs = DefaultParse({"/define:1", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "1 ^^ ^^ ").WithLocation(1, 1)) End Sub <Fact> Public Sub CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics() Dim parsedArgs = DefaultParse({"/langversion:1000", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("langversion", "1000").WithLocation(1, 1)) End Sub <WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")> <ConditionalFact(GetType(IsEnglishLocal))> Public Sub MissingCompilerAssembly() Dim dir = Temp.CreateDirectory() Dim vbcPath = dir.CopyFile(s_basicCompilerExecutable).Path dir.CopyFile(GetType(Compilation).Assembly.Location) ' Missing Microsoft.CodeAnalysis.VisualBasic.dll. Dim result = ProcessUtilities.Run(vbcPath, arguments:="/nologo /t:library unknown.vb", workingDirectory:=dir.Path) Assert.Equal(1, result.ExitCode) Assert.Equal( $"Could not load file or assembly '{GetType(VisualBasicCompilation).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()) ' Missing System.Collections.Immutable.dll. dir.CopyFile(GetType(VisualBasicCompilation).Assembly.Location) result = ProcessUtilities.Run(vbcPath, arguments:="/nologo /t:library unknown.vb", workingDirectory:=dir.Path) Assert.Equal(1, result.ExitCode) Assert.Equal( $"Could not load file or assembly '{GetType(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()) End Sub <ConditionalFact(GetType(WindowsOnly))> <WorkItem(21935, "https://github.com/dotnet/roslyn/issues/21935")> Public Sub PdbPathNotEmittedWithoutPdb() Dim dir = Temp.CreateDirectory() Dim src = MakeTrivialExe(directory:=dir.Path) Dim args = {"/nologo", src, "/out:a.exe", "/debug-"} Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, args) Dim exitCode = vbc.Run(outWriter) Assert.Equal(0, exitCode) Dim exePath = Path.Combine(dir.Path, "a.exe") Assert.True(File.Exists(exePath)) Using peStream = File.OpenRead(exePath) Using peReader = New PEReader(peStream) Dim debugDirectory = peReader.PEHeaders.PEHeader.DebugTableDirectory Assert.Equal(0, debugDirectory.Size) Assert.Equal(0, debugDirectory.RelativeVirtualAddress) End Using End Using End Sub <Fact> Public Sub StrongNameProviderWithCustomTempPath() Dim tempDir = Temp.CreateDirectory() Dim workingDir = Temp.CreateDirectory() workingDir.CreateFile("a.vb") Dim vbc = New MockVisualBasicCompiler(Nothing, New BuildPaths("", workingDir.Path, Nothing, tempDir.Path), {"/features:UseLegacyStrongNameProvider", "/nostdlib", "a.vb"}) Dim comp = vbc.CreateCompilation(TextWriter.Null, New TouchedFileLogger(), NullErrorLogger.Instance, Nothing) Assert.False(comp.SignUsingBuilder) End Sub Private Function MakeTrivialExe(Optional directory As String = Nothing) As String Return Temp.CreateFile(directory:=directory, prefix:="", extension:=".vb").WriteAllText(" Class Program Public Shared Sub Main() End Sub End Class").Path End Function <Fact> <WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")> Public Sub InvalidPathCharacterInPathMap() Dim filePath = Temp.CreateFile().WriteAllText("").Path Dim compiler = New MockVisualBasicCompiler(Nothing, _baseDirectory, { filePath, "/debug:embedded", "/pathmap:test\\=""", "/target:library", "/preferreduilang:en" }) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = compiler.Run(outWriter) Assert.Equal(1, exitCode) Assert.Contains("vbc : error BC37253: The pathmap option was incorrectly formatted.", outWriter.ToString(), StringComparison.Ordinal) End Sub <WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/38454")> Public Sub TestSuppression_CompilerWarning() ' warning BC40008 : 'C' is obsolete Dim source = " Imports System <Obsolete> Class C End Class Class D Inherits C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' Verify that compiler warning BC40008 is reported. Dim output = VerifyOutput(dir, file, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False) Assert.Contains("warning BC40008", output, StringComparison.Ordinal) ' Verify that compiler warning BC40008 is suppressed with diagnostic suppressor ' and info diagnostic is logged with programmatic suppression information. Dim suppressor = New DiagnosticSuppressorForId("BC40008") ' Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' Dim suppressionMessage = String.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "C"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification) Dim suppressors = ImmutableArray.Create(Of DiagnosticAnalyzer)(suppressor) output = VerifyOutput(dir, file, expectedInfoCount:=1, expectedWarningCount:=0, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=suppressors) Assert.DoesNotContain("warning BC40008", output, StringComparison.Ordinal) Assert.Contains("info SP0001", output, StringComparison.Ordinal) Assert.Contains(suppressionMessage, output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/38454")> Public Sub TestSuppression_CompilerWarningAsError() ' warning BC40008 : 'C' is obsolete Dim source = " Imports System <Obsolete> Class C End Class Class D Inherits C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' Verify that compiler warning BC40008 is reported. Dim output = VerifyOutput(dir, file, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False) Assert.Contains("warning BC40008", output, StringComparison.Ordinal) ' Verify that compiler warning BC40008 is reported as error for /warnaserror. output = VerifyOutput(dir, file, expectedErrorCount:=1, additionalFlags:={"/warnaserror+"}, includeCurrentAssemblyAsAnalyzerReference:=False) Assert.Contains("error BC40008", output, StringComparison.Ordinal) ' Verify that compiler warning BC40008 is suppressed with diagnostic suppressor even with /warnaserror ' and info diagnostic is logged with programmatic suppression information. Dim suppressor = New DiagnosticSuppressorForId("BC40008") Dim suppressors = ImmutableArray.Create(Of DiagnosticAnalyzer)(suppressor) output = VerifyOutput(dir, file, expectedInfoCount:=1, expectedWarningCount:=0, expectedErrorCount:=0, additionalFlags:={"/warnaserror+"}, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=suppressors) Assert.DoesNotContain($"warning BC40008", output, StringComparison.Ordinal) Assert.DoesNotContain($"error BC40008", output, StringComparison.Ordinal) ' Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' Dim suppressionMessage = String.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "C"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification) Assert.Contains("info SP0001", output, StringComparison.Ordinal) Assert.Contains(suppressionMessage, output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")> <Fact> Public Sub TestNoSuppression_CompilerError() ' warning BC30203 : Identifier expected Dim source = " Class End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' Verify that compiler error BC30203 is reported. Dim output = VerifyOutput(dir, file, expectedErrorCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False) Assert.Contains("error BC30203", output, StringComparison.Ordinal) ' Verify that compiler error BC30203 cannot be suppressed with diagnostic suppressor. Dim analyzers = ImmutableArray.Create(Of DiagnosticAnalyzer)(New DiagnosticSuppressorForId("BC30203")) output = VerifyOutput(dir, file, expectedErrorCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzers) Assert.Contains("error BC30203", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/38454")> Public Sub TestSuppression_AnalyzerWarning() Dim source = " Class C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' Verify that analyzer warning is reported. Dim analyzer = New CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable:=True) Dim analyzers = ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer) Dim output = VerifyOutput(dir, file, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzers) Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) ' Verify that analyzer warning is suppressed with diagnostic suppressor ' and info diagnostic is logged with programmatic suppression information. Dim suppressor = New DiagnosticSuppressorForId(analyzer.Descriptor.Id) ' Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' Dim suppressionMessage = String.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, analyzer.Descriptor.MessageFormat, suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification) Dim analyzerAndSuppressor = ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer, suppressor) output = VerifyOutput(dir, file, expectedInfoCount:=1, expectedWarningCount:=0, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzerAndSuppressor) Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) Assert.Contains("info SP0001", output, StringComparison.Ordinal) Assert.Contains(suppressionMessage, output, StringComparison.Ordinal) ' Verify that analyzer warning is reported as error for /warnaserror. output = VerifyOutput(dir, file, expectedErrorCount:=1, additionalFlags:={"/warnaserror+"}, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzers) Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) ' Verify that analyzer warning is suppressed with diagnostic suppressor even with /warnaserror ' and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(dir, file, expectedInfoCount:=1, expectedWarningCount:=0, expectedErrorCount:=0, additionalFlags:={"/warnaserror+"}, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzerAndSuppressor) Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) Assert.Contains("info SP0001", output, StringComparison.Ordinal) Assert.Contains(suppressionMessage, output, StringComparison.Ordinal) ' Verify that "NotConfigurable" analyzer warning cannot be suppressed with diagnostic suppressor even with /warnaserror. analyzer = New CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable:=False) suppressor = New DiagnosticSuppressorForId(analyzer.Descriptor.Id) analyzerAndSuppressor = ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer, suppressor) output = VerifyOutput(dir, file, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzerAndSuppressor) Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")> <Fact> Public Sub TestNoSuppression_AnalyzerError() Dim source = " Class C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' Verify that analyzer error is reported. Dim analyzer = New CompilationAnalyzerWithSeverity(DiagnosticSeverity.Error, configurable:=True) Dim analyzers = ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer) Dim output = VerifyOutput(dir, file, expectedErrorCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzers) Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) ' Verify that analyzer error cannot be suppressed with diagnostic suppressor. Dim suppressor = New DiagnosticSuppressorForId(analyzer.Descriptor.Id) Dim analyzerAndSuppressor = ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer, suppressor) output = VerifyOutput(dir, file, expectedErrorCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzerAndSuppressor) Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <Theory> <InlineData(True)> <InlineData(False)> <WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")> Public Sub CompilerWarnAsErrorDoesNotEmit(ByVal warnAsError As Boolean) ' warning BC40008 : 'C' is obsolete Dim source = " Imports System <Obsolete> Class C End Class Class D Inherits C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("temp.vb") file.WriteAllText(source) Dim docName As String = "doc.xml" Dim additionalFlags = {$"/doc:{docName}", "/debug:full"} If warnAsError Then additionalFlags = additionalFlags.Append("/warnaserror").AsArray() End If Dim expectedErrorCount = If(warnAsError, 1, 0) Dim expectedWarningCount = If(Not warnAsError, 1, 0) Dim output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags, expectedErrorCount:=expectedErrorCount, expectedWarningCount:=expectedWarningCount) Dim expectedOutput = If(warnAsError, "error BC40008", "warning BC40008") Assert.Contains(expectedOutput, output) Dim binaryPath As String = Path.Combine(dir.Path, "temp.dll") Assert.True(IO.File.Exists(binaryPath) = Not warnAsError) Dim pdbPath As String = Path.Combine(dir.Path, "temp.pdb") Assert.True(IO.File.Exists(pdbPath) = Not warnAsError) Dim docPath As String = Path.Combine(dir.Path, docName) Assert.True(IO.File.Exists(docPath) = Not warnAsError) End Sub <Theory> <InlineData(True)> <InlineData(False)> <WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")> Public Sub AnalyzerConfigSeverityEscalationToErrorDoesNotEmit(ByVal analyzerConfigSetToError As Boolean) ' warning BC40008 : 'C' is obsolete Dim source = " Imports System <Obsolete> Class C End Class Class D Inherits C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("temp.vb") file.WriteAllText(source) Dim docName As String = "doc.xml" Dim additionalFlags = {$"/doc:{docName}", "/debug:full"} If analyzerConfigSetToError Then Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(" [*.vb] dotnet_diagnostic.bc40008.severity = error") additionalFlags = additionalFlags.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray() End If Dim expectedErrorCount = If(analyzerConfigSetToError, 1, 0) Dim expectedWarningCount = If(Not analyzerConfigSetToError, 1, 0) Dim output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags, expectedErrorCount:=expectedErrorCount, expectedWarningCount:=expectedWarningCount) Dim expectedOutput = If(analyzerConfigSetToError, "error BC40008", "warning BC40008") Assert.Contains(expectedOutput, output) Dim binaryPath As String = Path.Combine(dir.Path, "temp.dll") Assert.True(IO.File.Exists(binaryPath) = Not analyzerConfigSetToError) Dim pdbPath As String = Path.Combine(dir.Path, "temp.pdb") Assert.True(IO.File.Exists(pdbPath) = Not analyzerConfigSetToError) Dim docPath As String = Path.Combine(dir.Path, docName) Assert.True(IO.File.Exists(docPath) = Not analyzerConfigSetToError) End Sub <Theory> <InlineData(True)> <InlineData(False)> <WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")> Public Sub RulesetSeverityEscalationToErrorDoesNotEmit(ByVal rulesetSetToError As Boolean) ' warning BC40008 : 'C' is obsolete Dim source = " Imports System <Obsolete> Class C End Class Class D Inherits C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("temp.vb") file.WriteAllText(source) Dim docName As String = "doc.xml" Dim additionalFlags = {$"/doc:{docName}", "/debug:full"} If rulesetSetToError Then Dim rulesetSource = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <Rules AnalyzerId="Microsoft.CodeAnalysis" RuleNamespace="Microsoft.CodeAnalysis"> <Rule Id="BC40008" Action="Error"/> </Rules> </RuleSet> Dim ruleSetFile = CreateRuleSetFile(rulesetSource) additionalFlags = additionalFlags.Append("/ruleset:" + ruleSetFile.Path).ToArray() End If Dim expectedErrorCount = If(rulesetSetToError, 1, 0) Dim expectedWarningCount = If(Not rulesetSetToError, 1, 0) Dim output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags, expectedErrorCount:=expectedErrorCount, expectedWarningCount:=expectedWarningCount) Dim expectedOutput = If(rulesetSetToError, "error BC40008", "warning BC40008") Assert.Contains(expectedOutput, output) Dim binaryPath As String = Path.Combine(dir.Path, "temp.dll") Assert.True(IO.File.Exists(binaryPath) = Not rulesetSetToError) Dim pdbPath As String = Path.Combine(dir.Path, "temp.pdb") Assert.True(IO.File.Exists(pdbPath) = Not rulesetSetToError) Dim docPath As String = Path.Combine(dir.Path, docName) Assert.True(IO.File.Exists(docPath) = Not rulesetSetToError) End Sub <Theory> <InlineData(True)> <InlineData(False)> <WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")> Public Sub AnalyzerWarnAsErrorDoesNotEmit(ByVal warnAsError As Boolean) Dim source = " Class C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("temp.vb") file.WriteAllText(source) Dim expectedErrorCount = If(warnAsError, 2, 0) Dim expectedWarningCount = If(Not warnAsError, 2, 0) Dim analyzer As DiagnosticAnalyzer = New WarningDiagnosticAnalyzer() ' Reports 2 warnings for each named type. Dim additionalFlags = If(warnAsError, {"/warnaserror"}, Nothing) Dim output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags, expectedErrorCount:=expectedErrorCount, expectedWarningCount:=expectedWarningCount, analyzers:=ImmutableArray.Create(analyzer)) Dim expectedODiagnosticSeverity = If(warnAsError, "error", "warning") Assert.Contains($"{expectedODiagnosticSeverity} {WarningDiagnosticAnalyzer.Warning01.Id}", output) Assert.Contains($"{expectedODiagnosticSeverity} {WarningDiagnosticAnalyzer.Warning03.Id}", output) Dim binaryPath As String = Path.Combine(dir.Path, "temp.dll") Assert.True(IO.File.Exists(binaryPath) = Not warnAsError) End Sub <WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")> <CombinatorialData, Theory> Public Sub TestAnalyzerFilteringBasedOnSeverity(ByVal defaultSeverity As DiagnosticSeverity, ByVal errorlog As Boolean) ' This test verifies that analyzer execution is skipped at build time for the following: ' 1. Analyzer reporting Hidden diagnostics ' 2. Analyzer reporting Info diagnostics, when /errorlog is not specified Dim analyzerShouldBeSkipped = defaultSeverity = DiagnosticSeverity.Hidden OrElse defaultSeverity = DiagnosticSeverity.Info AndAlso Not errorlog ' We use an analyzer that throws an exception on every analyzer callback. ' So an AD0001 analyzer exception diagnostic is reported if analyzer executed, otherwise not. Dim analyzer = New NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault:=True, defaultSeverity, throwOnAllNamedTypes:=True) Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.vb").WriteAllText(" Class C End Class") Dim args = {"/nologo", "/t:library", "/preferreduilang:en", src.Path} If errorlog Then args = args.Append("/errorlog:errorlog") End If Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, args, analyzer) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal(0, exitCode) Dim output = outWriter.ToString() If analyzerShouldBeSkipped Then Assert.Empty(output) Else Assert.Contains("warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+NamedTypeAnalyzerWithConfigurableEnabledByDefault' threw an exception of type 'System.NotImplementedException'", output, StringComparison.Ordinal) End If End Sub <WorkItem(47017, "https://github.com/dotnet/roslyn/issues/47017")> <CombinatorialData, Theory> Public Sub TestWarnAsErrorMinusDoesNotEnableDisabledByDefaultAnalyzers(defaultSeverity As DiagnosticSeverity, isEnabledByDefault As Boolean) ' This test verifies that '/warnaserror-:DiagnosticId' does not affect if analyzers are executed or skipped. ' Setup the analyzer to always throw an exception on analyzer callbacks for cases where we expect analyzer execution to be skipped: ' 1. Disabled by default analyzer, i.e. 'isEnabledByDefault == false'. ' 2. Default severity Hidden/Info: We only execute analyzers reporting Warning/Error severity diagnostics on command line builds. Dim analyzerShouldBeSkipped = Not isEnabledByDefault OrElse defaultSeverity = DiagnosticSeverity.Hidden OrElse defaultSeverity = DiagnosticSeverity.Info Dim analyzer = New NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity, throwOnAllNamedTypes:=analyzerShouldBeSkipped) Dim diagnosticId = analyzer.Descriptor.Id Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.cs").WriteAllText(" Class C End Class") ' Verify '/warnaserror-:DiagnosticId' behavior. Dim args = {"/warnaserror+", $"/warnaserror-:{diagnosticId}", "/nologo", "/t:library", "/preferreduilang:en", src.Path} Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, args, analyzer) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Dim expectedExitCode = If(Not analyzerShouldBeSkipped AndAlso defaultSeverity = DiagnosticSeverity.[Error], 1, 0) Assert.Equal(expectedExitCode, exitCode) Dim output = outWriter.ToString() If analyzerShouldBeSkipped Then Assert.Empty(output) Else Dim prefix = If(defaultSeverity = DiagnosticSeverity.Warning, "warning", "error") Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", output) End If End Sub <WorkItem(49446, "https://github.com/dotnet/roslyn/issues/49446")> <Theory> <InlineData(False, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Error)> <InlineData(True, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Warning)> <InlineData(False, DiagnosticSeverity.Warning, Nothing, DiagnosticSeverity.Error)> <InlineData(True, DiagnosticSeverity.Warning, Nothing, DiagnosticSeverity.Warning)> <InlineData(False, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Error)> <InlineData(True, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Warning)> <InlineData(False, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)> <InlineData(True, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)> Public Sub TestWarnAsErrorMinusDoesNotNullifyEditorConfig(warnAsErrorMinus As Boolean, defaultSeverity As DiagnosticSeverity, severityInConfigFile As DiagnosticSeverity?, expectedEffectiveSeverity As DiagnosticSeverity) Dim analyzer = New NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault:=True, defaultSeverity, throwOnAllNamedTypes:=False) Dim diagnosticId = analyzer.Descriptor.Id Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.vb").WriteAllText(" Class C End Class") Dim additionalFlags = {"/warnaserror+"} If severityInConfigFile.HasValue Then Dim severityString = DiagnosticDescriptor.MapSeverityToReport(severityInConfigFile.Value).ToAnalyzerConfigString() Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($" [*.vb] dotnet_diagnostic.{diagnosticId}.severity = {severityString}") additionalFlags = additionalFlags.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray() End If If warnAsErrorMinus Then additionalFlags = additionalFlags.Append($"/warnaserror-:{diagnosticId}").ToArray() End If Dim expectedWarningCount As Integer = 0, expectedErrorCount As Integer = 0 Select Case expectedEffectiveSeverity Case DiagnosticSeverity.Warning expectedWarningCount = 1 Case DiagnosticSeverity.[Error] expectedErrorCount = 1 Case Else Throw ExceptionUtilities.UnexpectedValue(expectedEffectiveSeverity) End Select VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, expectedWarningCount:=expectedWarningCount, expectedErrorCount:=expectedErrorCount, additionalFlags:=additionalFlags, analyzers:=ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) End Sub <Fact> <WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")> Public Sub GlobalAnalyzerConfigDiagnosticOptionsCanBeOverridenByCommandLine() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("temp.vb").WriteAllText(" Class C Private Sub M() Dim a As String End Sub End Class ") Dim globalConfig = dir.CreateFile(".globalconfig").WriteAllText(" is_global = true dotnet_diagnostic.BC42024.severity = error; ") Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(" [*.vb] dotnet_diagnostic.BC42024.severity = warning; ") Dim globalOption = "/analyzerconfig:" + globalConfig.Path Dim specificOption = "/analyzerconfig:" + analyzerConfig.Path VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, expectedWarningCount:=1) VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, expectedWarningCount:=0, additionalFlags:={"/nowarn:BC42024"}) VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, expectedErrorCount:=1, additionalFlags:={globalOption}) VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:BC42024", globalOption}) VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:42024", globalOption}) VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, expectedWarningCount:=1, additionalFlags:={globalOption, specificOption}) VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, expectedWarningCount:=0, additionalFlags:={"/nowarn:BC42024", globalOption, specificOption}) End Sub <Theory, CombinatorialData> <WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")> Public Sub WarnAsErrorIsRespectedForForWarningsConfiguredInRulesetOrGlobalConfig(useGlobalConfig As Boolean) Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("temp.vb").WriteAllText(" Class C Private Sub M() Dim a As String End Sub End Class") Dim additionalFlags = {"/warnaserror+"} If useGlobalConfig Then Dim globalConfig = dir.CreateFile(".globalconfig").WriteAllText($" is_global = true dotnet_diagnostic.BC42024.severity = warning; ") additionalFlags = additionalFlags.Append("/analyzerconfig:" & globalConfig.Path).ToArray() Else Dim ruleSetSource As String = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""15.0""> <Rules AnalyzerId=""Compiler"" RuleNamespace=""Compiler""> <Rule Id=""BC42024"" Action=""Warning"" /> </Rules> </RuleSet> " dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) additionalFlags = additionalFlags.Append("/ruleset:Rules.ruleset").ToArray() End If VerifyOutput(dir, src, additionalFlags:=additionalFlags, expectedErrorCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False) End Sub <Fact> <WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")> Public Sub GlobalAnalyzerConfigSpecificDiagnosticOptionsOverrideGeneralCommandLineOptions() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("temp.vb").WriteAllText(" Class C Private Sub M() Dim a As String End Sub End Class ") Dim globalConfig = dir.CreateFile(".globalconfig").WriteAllText(" is_global = true dotnet_diagnostic.BC42024.severity = none; ") VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror+", "/analyzerconfig:" + globalConfig.Path}) End Sub <Theory, CombinatorialData> Public Sub TestAdditionalFileAnalyzer(registerFromInitialize As Boolean) Dim srcDirectory = Temp.CreateDirectory() Dim source = " Class C End Class" Dim srcFile = srcDirectory.CreateFile("a.vb") srcFile.WriteAllText(source) Dim additionalText = "Additional Text" Dim additionalFile = srcDirectory.CreateFile("b.txt") additionalFile.WriteAllText(additionalText) Dim diagnosticSpan = New TextSpan(2, 2) Dim analyzer As DiagnosticAnalyzer = New AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan) Dim output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/additionalfile:" & additionalFile.Path}, analyzers:=ImmutableArray.Create(analyzer)) Assert.Contains("b.txt(1) : warning ID0001", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(srcDirectory.Path) End Sub <Theory> <InlineData("warning", "/warnaserror", True, False)> <InlineData("error", "/warnaserror", True, False)> <InlineData(Nothing, "/warnaserror", True, False)> <InlineData("warning", "/warnaserror:BC40008", True, False)> <InlineData("error", "/warnaserror:BC40008", True, False)> <InlineData(Nothing, "/warnaserror:BC40008", True, False)> <InlineData("warning", "/nowarn:BC40008", False, False)> <InlineData("error", "/nowarn:BC40008", False, False)> <InlineData(Nothing, "/nowarn:BC40008", False, False)> <InlineData("warning", Nothing, False, True)> <InlineData("error", Nothing, True, False)> <InlineData(Nothing, Nothing, False, True)> <WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")> Public Sub TestCompilationOptionsOverrideAnalyzerConfig_CompilerWarning(analyzerConfigSeverity As String, additionalArg As String, expectError As Boolean, expectWarning As Boolean) ' warning BC40008 : 'C' is obsolete Dim src = " Imports System <Obsolete> Class C End Class Class D Inherits C End Class" TestCompilationOptionsOverrideAnalyzerConfigCore(src, diagnosticId:="BC40008", analyzerConfigSeverity, additionalArg, expectError, expectWarning) End Sub <Theory> <InlineData("warning", "/warnaserror", True, False)> <InlineData("error", "/warnaserror", True, False)> <InlineData(Nothing, "/warnaserror", True, False)> <InlineData("warning", "/warnaserror:" & CompilationAnalyzerWithSeverity.DiagnosticId, True, False)> <InlineData("error", "/warnaserror:" & CompilationAnalyzerWithSeverity.DiagnosticId, True, False)> <InlineData(Nothing, "/warnaserror:" & CompilationAnalyzerWithSeverity.DiagnosticId, True, False)> <InlineData("warning", "/nowarn:" & CompilationAnalyzerWithSeverity.DiagnosticId, False, False)> <InlineData("error", "/nowarn:" & CompilationAnalyzerWithSeverity.DiagnosticId, False, False)> <InlineData(Nothing, "/nowarn:" & CompilationAnalyzerWithSeverity.DiagnosticId, False, False)> <InlineData("warning", Nothing, False, True)> <InlineData("error", Nothing, True, False)> <InlineData(Nothing, Nothing, False, True)> <WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")> Public Sub TestCompilationOptionsOverrideAnalyzerConfig_AnalyzerWarning(analyzerConfigSeverity As String, additionalArg As String, expectError As Boolean, expectWarning As Boolean) Dim analyzer = New CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable:=True) Dim src = " Class C End Class" TestCompilationOptionsOverrideAnalyzerConfigCore(src, CompilationAnalyzerWithSeverity.DiagnosticId, analyzerConfigSeverity, additionalArg, expectError, expectWarning, analyzer) End Sub Private Sub TestCompilationOptionsOverrideAnalyzerConfigCore( source As String, diagnosticId As String, analyzerConfigSeverity As String, additionalArg As String, expectError As Boolean, expectWarning As Boolean, ParamArray analyzers As DiagnosticAnalyzer()) Assert.True(Not expectError OrElse Not expectWarning) Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("temp.vb").WriteAllText(source) Dim additionalArgs = Array.Empty(Of String)() If analyzerConfigSeverity IsNot Nothing Then Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($" [*.vb] dotnet_diagnostic.{diagnosticId}.severity = {analyzerConfigSeverity}") additionalArgs = additionalArgs.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray() End If If Not String.IsNullOrEmpty(additionalArg) Then additionalArgs = additionalArgs.Append(additionalArg) End If Dim output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalArgs, expectedErrorCount:=If(expectError, 1, 0), expectedWarningCount:=If(expectWarning, 1, 0), analyzers:=analyzers.ToImmutableArrayOrEmpty()) If expectError Then Assert.Contains($"error {diagnosticId}", output) ElseIf expectWarning Then Assert.Contains($"warning {diagnosticId}", output) Else Assert.DoesNotContain(diagnosticId, output) End If End Sub <ConditionalFact(GetType(CoreClrOnly), Reason:="Can't load a coreclr targeting generator on net framework / mono")> Public Sub TestGeneratorsCantTargetNetFramework() Dim directory = Temp.CreateDirectory() Dim src = directory.CreateFile("test.vb").WriteAllText(" Class C End Class") 'Core Dim coreGenerator = EmitGenerator(".NETCoreApp,Version=v5.0") VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/analyzer:" & coreGenerator}) 'NetStandard Dim nsGenerator = EmitGenerator(".NETStandard,Version=v2.0") VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/analyzer:" & nsGenerator}) 'NoTarget Dim ntGenerator = EmitGenerator(targetFramework:=Nothing) VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/analyzer:" & ntGenerator}) 'Framework Dim frameworkGenerator = EmitGenerator(".NETFramework,Version=v4.7.2") Dim output = VerifyOutput(directory, src, expectedWarningCount:=2, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/analyzer:" & frameworkGenerator}) Assert.Contains("CS8850", output) Assert.Contains("CS8033", output) 'Framework, suppressed output = VerifyOutput(directory, src, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:CS8850", "/analyzer:" & frameworkGenerator}) Assert.Contains("CS8033", output) VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:CS8850,CS8033", "/analyzer:" & frameworkGenerator}) End Sub Private Function EmitGenerator(ByVal targetFramework As String) As String Dim targetFrameworkAttributeText As String = If(TypeOf targetFramework Is Object, $"<Assembly: System.Runtime.Versioning.TargetFramework(""{targetFramework}"")>", String.Empty) Dim generatorSource As String = $" Imports Microsoft.CodeAnalysis {targetFrameworkAttributeText} <Generator> Public Class Generator Inherits ISourceGenerator Public Sub Execute(ByVal context As GeneratorExecutionContext) End Sub Public Sub Initialize(ByVal context As GeneratorInitializationContext) End Sub End Class " Dim directory = Temp.CreateDirectory() Dim generatorPath = Path.Combine(directory.Path, "generator.dll") Dim compilation = VisualBasicCompilation.Create($"generator_{targetFramework}", {VisualBasicSyntaxTree.ParseText(generatorSource)}, TargetFrameworkUtil.GetReferences(Roslyn.Test.Utilities.TargetFramework.Standard, {MetadataReference.CreateFromAssemblyInternal(GetType(ISourceGenerator).Assembly)}), New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) compilation.VerifyDiagnostics() Dim result = compilation.Emit(generatorPath) Assert.[True](result.Success) Return generatorPath End Function End Class <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend MustInherit Class MockAbstractDiagnosticAnalyzer Inherits DiagnosticAnalyzer Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterCompilationStartAction( Sub(startContext As CompilationStartAnalysisContext) startContext.RegisterCompilationEndAction(AddressOf AnalyzeCompilation) CreateAnalyzerWithinCompilation(startContext) End Sub) End Sub Public MustOverride Sub CreateAnalyzerWithinCompilation(context As CompilationStartAnalysisContext) Public MustOverride Sub AnalyzeCompilation(context As CompilationAnalysisContext) End Class <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class HiddenDiagnosticAnalyzer Inherits MockAbstractDiagnosticAnalyzer Friend Shared ReadOnly Hidden01 As DiagnosticDescriptor = New DiagnosticDescriptor("Hidden01", "", "Throwing a diagnostic for #ExternalSource", "", DiagnosticSeverity.Hidden, isEnabledByDefault:=True) Public Overrides Sub CreateAnalyzerWithinCompilation(context As CompilationStartAnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ExternalSourceDirectiveTrivia) End Sub Public Overrides Sub AnalyzeCompilation(context As CompilationAnalysisContext) End Sub Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Hidden01) End Get End Property Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) context.ReportDiagnostic(Diagnostic.Create(Hidden01, context.Node.GetLocation())) End Sub End Class <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class InfoDiagnosticAnalyzer Inherits MockAbstractDiagnosticAnalyzer Friend Shared ReadOnly Info01 As DiagnosticDescriptor = New DiagnosticDescriptor("Info01", "", "Throwing a diagnostic for #Enable", "", DiagnosticSeverity.Info, isEnabledByDefault:=True) Friend Shared ReadOnly Info02 As DiagnosticDescriptor = New DiagnosticDescriptor("Info02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides Sub CreateAnalyzerWithinCompilation(context As CompilationStartAnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.EnableWarningDirectiveTrivia) End Sub Public Overrides Sub AnalyzeCompilation(context As CompilationAnalysisContext) End Sub Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Info01, Info02) End Get End Property Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) context.ReportDiagnostic(Diagnostic.Create(Info01, context.Node.GetLocation())) End Sub End Class <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class WarningDiagnosticAnalyzer Inherits MockAbstractDiagnosticAnalyzer Friend Shared ReadOnly Warning01 As DiagnosticDescriptor = New DiagnosticDescriptor("Warning01", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Friend Shared ReadOnly Warning02 As DiagnosticDescriptor = New DiagnosticDescriptor("Warning02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Friend Shared ReadOnly Warning03 As DiagnosticDescriptor = New DiagnosticDescriptor("Warning03", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Public Overrides Sub CreateAnalyzerWithinCompilation(context As CompilationStartAnalysisContext) context.RegisterSymbolAction(AddressOf AnalyzeSymbol, SymbolKind.NamedType) End Sub Public Overrides Sub AnalyzeCompilation(context As CompilationAnalysisContext) End Sub Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Warning01, Warning02, Warning03) End Get End Property Public Sub AnalyzeSymbol(context As SymbolAnalysisContext) context.ReportDiagnostic(Diagnostic.Create(Warning01, context.Symbol.Locations.First())) context.ReportDiagnostic(Diagnostic.Create(Warning03, context.Symbol.Locations.First())) End Sub End Class <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class ErrorDiagnosticAnalyzer Inherits MockAbstractDiagnosticAnalyzer Friend Shared ReadOnly Error01 As DiagnosticDescriptor = New DiagnosticDescriptor("Error01", "", "Throwing a diagnostic for #Disable", "", DiagnosticSeverity.Error, isEnabledByDefault:=True) Public Overrides Sub CreateAnalyzerWithinCompilation(context As CompilationStartAnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.DisableWarningDirectiveTrivia) End Sub Public Overrides Sub AnalyzeCompilation(context As CompilationAnalysisContext) End Sub Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Error01) End Get End Property Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) context.ReportDiagnostic(Diagnostic.Create(Error01, context.Node.GetLocation())) End Sub End Class Friend Class AdditionalFileDiagnosticAnalyzer Inherits MockAbstractDiagnosticAnalyzer Friend Shared ReadOnly Rule As DiagnosticDescriptor = New DiagnosticDescriptor("AdditionalFileDiagnostic", "", "Additional File Diagnostic: {0}", "", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Private ReadOnly _nonCompilerInputFile As String Public Sub New(nonCompilerInputFile As String) _nonCompilerInputFile = nonCompilerInputFile End Sub Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Rule) End Get End Property Public Overrides Sub AnalyzeCompilation(context As CompilationAnalysisContext) End Sub Public Overrides Sub CreateAnalyzerWithinCompilation(context As CompilationStartAnalysisContext) context.RegisterCompilationEndAction(AddressOf CompilationEndAction) End Sub Private Sub CompilationEndAction(context As CompilationAnalysisContext) ' Diagnostic reported on additionals file, with valid span. For Each additionalFile In context.Options.AdditionalFiles ReportDiagnostic(additionalFile.Path, context) Next ' Diagnostic reported on an additional file, but with an invalid span. ReportDiagnostic(context.Options.AdditionalFiles.First().Path, context, New TextSpan(0, 1000000)) ' Overflow span ' Diagnostic reported on a file which is not an input for the compiler. ReportDiagnostic(_nonCompilerInputFile, context) ' Diagnostic reported on a non-existent file. ReportDiagnostic("NonExistentPath", context) End Sub Private Sub ReportDiagnostic(path As String, context As CompilationAnalysisContext, Optional span As TextSpan = Nothing) If span = Nothing Then span = New TextSpan(0, 11) End If Dim linePosSpan = New LinePositionSpan(New LinePosition(0, 0), New LinePosition(0, span.End)) Dim diagLocation = Location.Create(path, span, linePosSpan) Dim diag = Diagnostic.Create(Rule, diagLocation, IO.Path.GetFileNameWithoutExtension(path)) context.ReportDiagnostic(diag) 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.Collections.Immutable Imports System.ComponentModel Imports System.Globalization Imports System.IO Imports System.IO.MemoryMappedFiles Imports System.Reflection Imports System.Reflection.Metadata Imports System.Reflection.PortableExecutable Imports System.Runtime.InteropServices Imports System.Security.Cryptography Imports System.Text Imports System.Text.RegularExpressions Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.DiaSymReader Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.SharedResourceHelpers Imports Roslyn.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests Partial Public Class CommandLineTests Inherits BasicTestBase Private Shared ReadOnly s_basicCompilerExecutable As String = Path.Combine( Path.GetDirectoryName(GetType(CommandLineTests).Assembly.Location), Path.Combine("dependency", "vbc.exe")) Private Shared ReadOnly s_DotnetCscRun As String = If(ExecutionConditionUtil.IsMono, "mono", String.Empty) Private ReadOnly _baseDirectory As String = TempRoot.Root Private Shared ReadOnly s_defaultSdkDirectory As String = RuntimeEnvironment.GetRuntimeDirectory() Private Shared ReadOnly s_compilerVersion As String = CommonCompiler.GetProductVersion(GetType(CommandLineTests)) Private Shared Function DefaultParse(args As IEnumerable(Of String), baseDirectory As String, Optional sdkDirectory As String = Nothing, Optional additionalReferenceDirectories As String = Nothing) As VisualBasicCommandLineArguments sdkDirectory = If(sdkDirectory, s_defaultSdkDirectory) Return VisualBasicCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories) End Function Private Shared Function FullParse(commandLine As String, baseDirectory As String, Optional sdkDirectory As String = Nothing, Optional additionalReferenceDirectories As String = Nothing) As VisualBasicCommandLineArguments sdkDirectory = If(sdkDirectory, s_defaultSdkDirectory) Dim args = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments:=True) Return VisualBasicCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories) End Function Private Shared Function InteractiveParse(args As IEnumerable(Of String), baseDirectory As String, Optional sdkDirectory As String = Nothing, Optional additionalReferenceDirectories As String = Nothing) As VisualBasicCommandLineArguments sdkDirectory = If(sdkDirectory, s_defaultSdkDirectory) Return VisualBasicCommandLineParser.Script.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories) End Function <Fact> Public Sub SimpleAnalyzerConfig() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.vb").WriteAllText(" Class C Sub M() Dim x As Integer End Sub End Class") Dim additionalFile = dir.CreateFile("file.txt") Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(" [*.vb] dotnet_diagnostic.bc42024.severity = none") Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path}) Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal(0, exitCode) Assert.Equal("", outWriter.ToString()) Assert.Null(cmd.AnalyzerOptions) End Sub <Fact> Public Sub AnalyzerConfigWithOptions() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.vb").WriteAllText(" Class C Sub M() Dim x As Integer End Sub End Class") Dim additionalFile = dir.CreateFile("file.txt") Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(" [*.vb] dotnet_diagnostic.bc42024.severity = none dotnet_diagnostic.warning01.severity = none dotnet_diagnostic.Warning03.severity = none my_option = my_val [*.txt] dotnet_diagnostic.bc42024.severity = none my_option2 = my_val2") Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:42376", "/additionalfile:" + additionalFile.Path, src.Path}) Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal(0, exitCode) Assert.Equal("", outWriter.ToString()) Dim comp = cmd.Compilation Dim tree = comp.SyntaxTrees.Single() Dim syntaxTreeOptions = comp.Options.SyntaxTreeOptionsProvider Dim report As ReportDiagnostic Assert.True(syntaxTreeOptions.TryGetDiagnosticValue(tree, "BC42024", CancellationToken.None, report)) Assert.Equal(ReportDiagnostic.Suppress, report) Assert.True(syntaxTreeOptions.TryGetDiagnosticValue(tree, "warning01", CancellationToken.None, report)) Assert.Equal(ReportDiagnostic.Suppress, report) Assert.True(syntaxTreeOptions.TryGetDiagnosticValue(tree, "warning03", CancellationToken.None, report)) Assert.Equal(ReportDiagnostic.Suppress, report) Assert.False(syntaxTreeOptions.TryGetDiagnosticValue(tree, "warning02", CancellationToken.None, report)) Dim provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider Dim options = provider.GetOptions(tree) Assert.NotNull(options) Dim val As String = Nothing Assert.True(options.TryGetValue("my_option", val)) Assert.Equal("my_val", val) Assert.False(options.TryGetValue("my_option2", Nothing)) Assert.False(options.TryGetValue("dotnet_diagnostic.bc42024.severity", Nothing)) options = provider.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()) Assert.NotNull(options) Assert.True(options.TryGetValue("my_option2", val)) Assert.Equal("my_val2", val) Assert.False(options.TryGetValue("my_option", Nothing)) Assert.False(options.TryGetValue("dotnet_diagnostic.bc42024.severity", Nothing)) End Sub <Fact> Public Sub AnalyzerConfigBadSeverity() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.vb").WriteAllText(" Class C Sub M() Dim x As Integer End Sub End Class") Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(" [*.vb] dotnet_diagnostic.BC42024.severity = garbage") Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path}) Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal(0, exitCode) Assert.Equal( $"vbc : warning InvalidSeverityInAnalyzerConfig: The diagnostic 'bc42024' was given an invalid severity 'garbage' in the analyzer config file at '{analyzerConfig.Path}'. {src.Path}(4) : warning BC42024: Unused local variable: 'x'. Dim x As Integer ~ ", outWriter.ToString()) End Sub <Fact> Public Sub AnalyzerConfigsInSameDir() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.cs").WriteAllText(" Class C Sub M() Dim x As Integer End Sub End Class") Dim configText = " [*.cs] dotnet_diagnostic.cs0169.severity = suppress" Dim analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText) Dim analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText) Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal(1, exitCode) Assert.Equal( $"vbc : error BC42500: Multiple analyzer config files cannot be in the same directory ('{dir.Path}').", outWriter.ToString().TrimEnd()) End Sub <Fact> <WorkItem(34101, "https://github.com/dotnet/roslyn/issues/34101")> Public Sub SuppressedWarnAsErrorsStillEmit() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("temp.vb").WriteAllText(" #Disable Warning BC42302 Module Module1 Sub Main() Dim x = 42 ''' <test /> End Sub End Module") Const docName As String = "doc.xml" Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/errorlog:errorlog", $"/doc:{docName}", "/warnaserror", src.Path}) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal("", outWriter.ToString()) Assert.Equal(0, exitCode) Dim exePath = Path.Combine(dir.Path, "temp.exe") Assert.True(File.Exists(exePath)) End Sub <Fact> Public Sub XmlMemoryMapped() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("temp.cs").WriteAllText(" Class C End Class") Dim docName As String = "doc.xml" Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/t:library", "/preferreduilang:en", $"/doc:{docName}", src.Path}) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal(0, exitCode) Assert.Equal("", outWriter.ToString()) Dim xmlPath = Path.Combine(dir.Path, docName) Using fileStream = New FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) Using mmf = MemoryMappedFile.CreateFromFile(fileStream, "xmlMap", 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen:=True) exitCode = cmd.Run(outWriter) Assert.Equal(1, exitCode) Assert.StartsWith($"vbc : error BC2012: can't open '{xmlPath}' for writing:", outWriter.ToString()) End Using End Using End Sub <Fact> <WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")> Public Sub CompilerBinariesAreAnyCPU() Assert.Equal(ProcessorArchitecture.MSIL, AssemblyName.GetAssemblyName(s_basicCompilerExecutable).ProcessorArchitecture) End Sub <Fact, WorkItem(546322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546322")> Public Sub NowarnWarnaserrorTest() Dim src As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/nowarn", "/warnaserror-", src}) Assert.Equal(cmd.Arguments.CompilationOptions.GeneralDiagnosticOption, ReportDiagnostic.Suppress) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/nowarn", "/warnaserror", src}) Assert.Equal(cmd.Arguments.CompilationOptions.GeneralDiagnosticOption, ReportDiagnostic.Error) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/nowarn", "/warnaserror+", src}) Assert.Equal(cmd.Arguments.CompilationOptions.GeneralDiagnosticOption, ReportDiagnostic.Error) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/warnaserror-", "/nowarn", src}) Assert.Equal(cmd.Arguments.CompilationOptions.GeneralDiagnosticOption, ReportDiagnostic.Suppress) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/warnaserror", "/nowarn", src}) Assert.Equal(cmd.Arguments.CompilationOptions.GeneralDiagnosticOption, ReportDiagnostic.Suppress) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/warnaserror+", "/nowarn", src}) Assert.Equal(cmd.Arguments.CompilationOptions.GeneralDiagnosticOption, ReportDiagnostic.Suppress) CleanupAllGeneratedFiles(src) End Sub <Fact> <WorkItem(21508, "https://github.com/dotnet/roslyn/issues/21508")> Public Sub ArgumentStartWithDashAndContainingSlash() Dim args As VisualBasicCommandLineArguments Dim folder = Temp.CreateDirectory() args = DefaultParse({"-debug+/debug:portable"}, folder.Path) args.Errors.AssertTheseDiagnostics(<errors> BC2007: unrecognized option '-debug+/debug:portable'; ignored BC2008: no input sources specified </errors>) End Sub <WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")> <Fact()> Public Sub CommandLineCompilationWithQuotedMainArgument() ' Arguments with quoted rootnamespace and main type are unquoted when ' the arguments are read in by the command line compiler. Dim src As String = Temp.CreateFile().WriteAllText(<text> Module Module1 Sub Main() End Sub End Module </text>.Value).Path Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/target:exe", "/rootnamespace:""test""", "/main:""test.Module1""", src}) Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) End Sub <Fact> Public Sub CreateCompilationWithKeyFile() Dim source = " Public Class C Public Shared Sub Main() End Sub End Class" Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source) Dim cmd = New MockVisualBasicCompiler(dir.Path, {"/nologo", "a.vb", "/keyfile:key.snk"}) Dim comp = cmd.CreateCompilation(TextWriter.Null, New TouchedFileLogger(), NullErrorLogger.Instance, Nothing) Assert.IsType(Of DesktopStrongNameProvider)(comp.Options.StrongNameProvider) End Sub <Fact> Public Sub CreateCompilationWithCryptoContainer() Dim source = " Public Class C Public Shared Sub Main() End Sub End Class" Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source) Dim cmd = New MockVisualBasicCompiler(dir.Path, {"/nologo", "a.vb", "/keycontainer:aaa"}) Dim comp = cmd.CreateCompilation(TextWriter.Null, New TouchedFileLogger(), NullErrorLogger.Instance, Nothing) Assert.True(TypeOf comp.Options.StrongNameProvider Is DesktopStrongNameProvider) End Sub <Fact> Public Sub CreateCompilationWithStrongNameFallbackCommand() Dim source = " Public Class C Public Shared Sub Main() End Sub End Class" Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source) Dim cmd = New MockVisualBasicCompiler(dir.Path, {"/nologo", "a.vb", "/features:UseLegacyStrongNameProvider"}) Dim comp = cmd.CreateCompilation(TextWriter.Null, New TouchedFileLogger(), NullErrorLogger.Instance, Nothing) Assert.True(TypeOf comp.Options.StrongNameProvider Is DesktopStrongNameProvider) End Sub <Fact> Public Sub ParseQuotedMainTypeAndRootnamespace() 'These options are always unquoted when parsed in VisualBasicCommandLineParser.Parse. Dim args = DefaultParse({"/rootnamespace:Test", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("Test", args.CompilationOptions.RootNamespace) args = DefaultParse({"/main:Test", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("Test", args.CompilationOptions.MainTypeName) args = DefaultParse({"/main:""Test""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("Test", args.CompilationOptions.MainTypeName) args = DefaultParse({"/rootnamespace:""Test""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("Test", args.CompilationOptions.RootNamespace) args = DefaultParse({"/rootnamespace:""test""", "/main:""test.Module1""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("test.Module1", args.CompilationOptions.MainTypeName) Assert.Equal("test", args.CompilationOptions.RootNamespace) ' Use of Cyrillic namespace args = DefaultParse({"/rootnamespace:""решения""", "/main:""решения.Module1""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("решения.Module1", args.CompilationOptions.MainTypeName) Assert.Equal("решения", args.CompilationOptions.RootNamespace) End Sub <WorkItem(722561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722561")> <Fact> Public Sub Bug_722561() Dim src As String = Temp.CreateFile().WriteAllText(<text> Public Class C End Class </text>.Value).Path ' Previous versions of the compiler used to report warnings (BC2026, BC2014) ' whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. ' We no longer generate a warning in such cases. Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/t:library", "/nowarn:-1", src}) Dim writer As New StringWriter() Dim result = cmd.Run(writer, Nothing) Assert.Equal(String.Empty, writer.ToString.Trim) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/t:library", "/nowarn:-12345678901234567890", src}) writer = New StringWriter() result = cmd.Run(writer, Nothing) Assert.Equal(String.Empty, writer.ToString.Trim) cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/t:library", "/nowarn:-1234567890123456789", src}) writer = New StringWriter() result = cmd.Run(writer, Nothing) Assert.Equal(String.Empty, writer.ToString.Trim) CleanupAllGeneratedFiles(src) End Sub <Fact> Public Sub VbcTest() Dim output As StringWriter = New StringWriter() Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:en"}) cmd.Run(output, Nothing) Assert.True(output.ToString().StartsWith(s_logoLine1, StringComparison.Ordinal), "vbc should print logo and help if no args specified") End Sub <Fact> Public Sub VbcNologo_1() Dim src As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim output As StringWriter = New StringWriter() Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/t:library", src}) Dim exitCode = cmd.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) CleanupAllGeneratedFiles(src) End Sub <Fact> Public Sub VbcNologo_1a() Dim src As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim output As StringWriter = New StringWriter() Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo+", "/t:library", src}) Dim exitCode = cmd.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) CleanupAllGeneratedFiles(src) End Sub <Fact> Public Sub VbcNologo_2() Dim src As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim output As StringWriter = New StringWriter() Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", "/preferreduilang:en", src}) Dim exitCode = cmd.Run(output, Nothing) Assert.Equal(0, exitCode) Dim patched As String = Regex.Replace(output.ToString().Trim(), "version \d+\.\d+\.\d+(-[\d\w]+)*", "version A.B.C-d") patched = ReplaceCommitHash(patched) Assert.Equal(<text> Microsoft (R) Visual Basic Compiler version A.B.C-d (HASH) Copyright (C) Microsoft Corporation. All rights reserved. </text>.Value.Replace(vbLf, vbCrLf).Trim, patched) CleanupAllGeneratedFiles(src) End Sub <Theory, InlineData("Microsoft (R) Visual Basic Compiler version A.B.C-d (<developer build>)", "Microsoft (R) Visual Basic Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual Basic Compiler version A.B.C-d (ABCDEF01)", "Microsoft (R) Visual Basic Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual Basic Compiler version A.B.C-d (abcdef90)", "Microsoft (R) Visual Basic Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual Basic Compiler version A.B.C-d (12345678)", "Microsoft (R) Visual Basic Compiler version A.B.C-d (HASH)")> Public Sub TestReplaceCommitHash(orig As String, expected As String) Assert.Equal(expected, ReplaceCommitHash(orig)) End Sub Private Shared Function ReplaceCommitHash(s As String) As String Return Regex.Replace(s, "(\((<developer build>|[a-fA-F0-9]{8})\))", "(HASH)") End Function <Fact> Public Sub VbcNologo_2a() Dim src As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim output As StringWriter = New StringWriter() Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo-", "/preferreduilang:en", "/t:library", src}) Dim exitCode = cmd.Run(output, Nothing) Assert.Equal(0, exitCode) Dim patched As String = Regex.Replace(output.ToString().Trim(), "version \d+\.\d+\.\d+(-[\w\d]+)*", "version A.B.C-d") patched = ReplaceCommitHash(patched) Assert.Equal(<text> Microsoft (R) Visual Basic Compiler version A.B.C-d (HASH) Copyright (C) Microsoft Corporation. All rights reserved. </text>.Value.Replace(vbLf, vbCrLf).Trim, patched) CleanupAllGeneratedFiles(src) End Sub <Fact()> Public Sub VbcUtf8Output_WithRedirecting_Off() Dim src As String = Temp.CreateFile().WriteAllText("♚", New System.Text.UTF8Encoding(False)).Path Dim tempOut = Temp.CreateFile() Dim output = ProcessUtilities.RunAndGetOutput("cmd", "/C """ & s_basicCompilerExecutable & """ /nologo /preferreduilang:en /t:library " & src & " > " & tempOut.Path, expectedRetCode:=1) Assert.Equal("", output.Trim()) Assert.Equal(<text> SRC.VB(1) : error BC30037: Character is not valid. ? ~ </text>.Value.Trim().Replace(vbLf, vbCrLf), tempOut.ReadAllText().Trim().Replace(src, "SRC.VB")) CleanupAllGeneratedFiles(src) End Sub <Fact()> Public Sub VbcUtf8Output_WithRedirecting_On() Dim src As String = Temp.CreateFile().WriteAllText("♚", New System.Text.UTF8Encoding(False)).Path Dim tempOut = Temp.CreateFile() Dim output = ProcessUtilities.RunAndGetOutput("cmd", "/C """ & s_basicCompilerExecutable & """ /utf8output /nologo /preferreduilang:en /t:library " & src & " > " & tempOut.Path, expectedRetCode:=1) Assert.Equal("", output.Trim()) Assert.Equal(<text> SRC.VB(1) : error BC30037: Character is not valid. ♚ ~ </text>.Value.Trim().Replace(vbLf, vbCrLf), tempOut.ReadAllText().Trim().Replace(src, "SRC.VB")) CleanupAllGeneratedFiles(src) End Sub <Fact> Public Sub VbcCompile_WithSourceCodeRedirectedViaStandardInput_ProducesRunnableProgram() Dim result As ProcessResult Dim tempDir As String = Temp.CreateDirectory().Path If RuntimeInformation.IsOSPlatform(OSPlatform.Windows) Then Dim sourceFile = Path.GetTempFileName() File.WriteAllText(sourceFile, " Module Program Sub Main() System.Console.WriteLine(""Hello World!"") End Sub End Module") result = ProcessUtilities.Run("cmd", $"/C {s_basicCompilerExecutable} /nologo /t:exe - < {sourceFile}", workingDirectory:=tempDir) File.Delete(sourceFile) Else result = ProcessUtilities.Run("/usr/bin/env", $"sh -c ""echo \ Module Program \ Sub Main\(\) \ System.Console.WriteLine\(\\\""Hello World\!\\\""\) \ End Sub \ End Module | {s_basicCompilerExecutable} /nologo /t:exe -""", workingDirectory:=tempDir, redirectStandardInput:=True) ' we are testing shell's piped/redirected stdin behavior explicitly ' instead of using Process.StandardInput.Write(), so we set ' redirectStandardInput to true, which implies that isatty of child ' process is false and thereby Console.IsInputRedirected will return ' true in vbc code. End If Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}") Dim output As String = If(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), ProcessUtilities.RunAndGetOutput("cmd.exe", $"/C ""{s_DotnetCscRun} -.exe""", expectedRetCode:=0, startFolder:=tempDir), ProcessUtilities.RunAndGetOutput("sh", $"-c ""{s_DotnetCscRun} -.exe""", expectedRetCode:=0, startFolder:=tempDir)) Assert.Equal("Hello World!", output.Trim()) End Sub <Fact> Public Sub VbcCompile_WithSourceCodeRedirectedViaStandardInput_ProducesLibrary() Dim name = Guid.NewGuid().ToString() & ".dll" Dim tempDir As String = Temp.CreateDirectory().Path Dim result As ProcessResult If RuntimeInformation.IsOSPlatform(OSPlatform.Windows) Then Dim sourceFile = Path.GetTempFileName() File.WriteAllText(sourceFile, " Class A public Function GetVal() As A Return Nothing End Function End Class") result = ProcessUtilities.Run("cmd", $"/C {s_basicCompilerExecutable} /nologo /t:library /out:{name} - < {sourceFile}", workingDirectory:=tempDir) File.Delete(sourceFile) Else result = ProcessUtilities.Run("/usr/bin/env", $"sh -c ""echo \ Class A \ Public Function GetVal\(\) As A \ Return Nothing \ End Function \ End Class | {s_basicCompilerExecutable} /nologo /t:library /out:{name} -""", workingDirectory:=tempDir, redirectStandardInput:=True) ' we are testing shell's piped/redirected stdin behavior explicitly ' instead of using Process.StandardInput.Write(), so we set ' redirectStandardInput to true, which implies that isatty of child ' process is false and thereby Console.IsInputRedirected will return ' true in vbc code. End If Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}") Dim assemblyName = System.Reflection.AssemblyName.GetAssemblyName(Path.Combine(tempDir, name)) Assert.Equal(name.Replace(".dll", ", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), assemblyName.ToString()) End Sub <Fact> Public Sub VbcCompile_WithRedirectedInputIndicatorAndStandardInputNotRedirected_ReportsBC56032() If Console.IsInputRedirected Then ' [applicable to both Windows and Unix] ' if our parent (xunit) process itself has input redirected, we cannot test this ' error case because our child process will inherit it and we cannot achieve what ' we are aiming for: isatty(0):true and thereby Console.IsInputerRedirected:false in ' child. running this case will make StreamReader to hang (waiting for input, that ' we do not propagate: parent.In->child.In). ' ' note: in Unix we can "close" fd0 by appending `0>&-` in the `sh -c` command below, ' but that will also not impact the result of isatty(), and in turn causes a different ' compiler error. Return End If Dim tempDir As String = Temp.CreateDirectory().Path Dim result As ProcessResult = If(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), ProcessUtilities.Run("cmd", $"/C ""{s_basicCompilerExecutable} /nologo /t:exe -""", workingDirectory:=tempDir), ProcessUtilities.Run("/usr/bin/env", $"sh -c ""{s_basicCompilerExecutable} /nologo /t:exe -""", workingDirectory:=tempDir)) Assert.True(result.ContainsErrors) Assert.Contains(CInt(ERRID.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected).ToString(), result.Output) End Sub <Fact()> Public Sub ResponseFiles1() Dim rsp As String = Temp.CreateFile().WriteAllText(<text> /r:System.dll /nostdlib /vbruntime- # this is ignored System.Console.WriteLine(&quot;*?&quot;); # this is error a.vb </text>.Value).Path Dim cmd = New MockVisualBasicCompiler(rsp, _baseDirectory, {"b.vb"}) AssertEx.Equal({"System.dll"}, cmd.Arguments.MetadataReferences.Select(Function(r) r.Reference)) AssertEx.Equal( { Path.Combine(_baseDirectory, "a.vb"), Path.Combine(_baseDirectory, "b.vb") }, cmd.Arguments.SourceFiles.Select(Function(file) file.Path)) Assert.NotEmpty(cmd.Arguments.Errors) CleanupAllGeneratedFiles(rsp) End Sub <WorkItem(685392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685392")> <Fact()> Public Sub ResponseFiles_RootNamespace() Dim rsp As String = Temp.CreateFile().WriteAllText(<text> /r:System.dll /rootnamespace:"Hello" a.vb </text>.Value).Path Dim cmd = New MockVisualBasicCompiler(rsp, _baseDirectory, {"b.vb"}) Assert.Equal("Hello", cmd.Arguments.CompilationOptions.RootNamespace) CleanupAllGeneratedFiles(rsp) End Sub Private Sub AssertGlobalImports(expectedImportStrings As String(), actualImports As GlobalImport()) Assert.Equal(expectedImportStrings.Length, actualImports.Count) For i = 0 To expectedImportStrings.Length - 1 Assert.Equal(expectedImportStrings(i), actualImports(i).Clause.ToString) Next End Sub <Fact> Public Sub ParseGlobalImports() Dim args = DefaultParse({"/imports: System ,System.Xml ,System.Linq", "a.vb"}, _baseDirectory) args.Errors.Verify() AssertEx.Equal({"System", "System.Xml", "System.Linq"}, args.CompilationOptions.GlobalImports.Select(Function(import) import.Clause.ToString())) args = DefaultParse({"/impORt: System,,,,,", "/IMPORTs:,,,Microsoft.VisualBasic,,System.IO", "a.vb"}, _baseDirectory) args.Errors.Verify() AssertEx.Equal({"System", "Microsoft.VisualBasic", "System.IO"}, args.CompilationOptions.GlobalImports.Select(Function(import) import.Clause.ToString())) args = DefaultParse({"/impORt: System, ,, ,,", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_ExpectedIdentifier), Diagnostic(ERRID.ERR_ExpectedIdentifier)) args = DefaultParse({"/impORt:", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("import", ":<str>")) args = DefaultParse({"/impORts:", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("imports", ":<import_list>")) args = DefaultParse({"/imports", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("imports", ":<import_list>")) args = DefaultParse({"/imports+", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/imports+")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact> Public Sub ParseInteractive() Dim args As VisualBasicCommandLineArguments args = DefaultParse({}, _baseDirectory) args.Errors.Verify() Assert.False(args.InteractiveMode) args = DefaultParse({"/i"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/i").WithLocation(1, 1), Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)}) Assert.False(args.InteractiveMode) args = InteractiveParse({}, _baseDirectory) args.Errors.Verify() Assert.True(args.InteractiveMode) args = InteractiveParse({"a.vb"}, _baseDirectory) args.Errors.Verify() Assert.False(args.InteractiveMode) args = InteractiveParse({"/i", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.InteractiveMode) args = InteractiveParse({"/i+", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.InteractiveMode) args = InteractiveParse({"/i+ /i-", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.False(args.InteractiveMode) For Each flag In {"i", "i+", "i-"} args = InteractiveParse({"/" + flag + ":arg"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("i").WithLocation(1, 1)) Next End Sub <Fact> Public Sub ParseInstrumentTestNames() Dim args As VisualBasicCommandLineArguments args = DefaultParse({}, _baseDirectory) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("instrument", ":<string>").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument:""""", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("instrument", ":<string>").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument:", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("instrument", ":<string>").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument:", "Test.Flag.Name", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("instrument", ":<string>").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument:InvalidOption", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument:None", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_InvalidInstrumentationKind).WithArguments("None").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({})) args = DefaultParse({"/instrument:""TestCoverage,InvalidOption""", "a.vb"}, _baseDirectory) args.Errors.Verify({Diagnostic(ERRID.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption").WithLocation(1, 1)}) Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({InstrumentationKind.TestCoverage})) args = DefaultParse({"/instrument:TestCoverage", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({InstrumentationKind.TestCoverage})) args = DefaultParse({"/instrument:""TestCoverage""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({InstrumentationKind.TestCoverage})) args = DefaultParse({"/instrument:""TESTCOVERAGE""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({InstrumentationKind.TestCoverage})) args = DefaultParse({"/instrument:TestCoverage,TestCoverage", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({InstrumentationKind.TestCoverage})) args = DefaultParse({"/instrument:TestCoverage", "/instrument:TestCoverage", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.EmitOptions.InstrumentationKinds.SequenceEqual({InstrumentationKind.TestCoverage})) End Sub <Fact> Public Sub ResponseFiles2() Dim rsp As String = Temp.CreateFile().WriteAllText(<text> /r:System /r:System.Core /r:System.Data /r:System.Data.DataSetExtensions /r:System.Xml /r:System.Xml.Linq /imports:System /imports:System.Collections.Generic /imports:System.Linq /imports:System.Text</text>.Value).Path Dim cmd = New MockVbi(rsp, _baseDirectory, {"b.vbx"}) ' TODO (tomat): mscorlib, vbruntime order 'AssertEx.Equal({GetType(Object).Assembly.Location, ' GetType(Microsoft.VisualBasic.Globals).Assembly.Location, ' "System", "System.Core", "System.Data", "System.Data.DataSetExtensions", "System.Xml", "System.Xml.Linq"}, ' cmd.Arguments.AssemblyReferences.Select(Function(r) ' Return If(r.Kind = ReferenceKind.AssemblyName, ' (DirectCast(r, AssemblyNameReference)).Name, ' (DirectCast(r, AssemblyFileReference)).Path) ' End Function)) AssertEx.Equal({"System", "System.Collections.Generic", "System.Linq", "System.Text"}, cmd.Arguments.CompilationOptions.GlobalImports.Select(Function(import) import.Clause.ToString())) End Sub <Fact, WorkItem(546028, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546028")> Public Sub Win32ResourceArguments() Dim args As String() = {"/win32manifest:..\here\there\everywhere\nonexistent"} Dim parsedArgs = DefaultParse(args, _baseDirectory) Dim compilation = CreateCompilationWithMscorlib40(New VisualBasicSyntaxTree() {}) Dim errors As IEnumerable(Of DiagnosticInfo) = Nothing CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_UnableToReadUacManifest2, Integer), errors.First().Code) Assert.Equal(2, errors.First().Arguments.Count()) args = {"/Win32icon:\bogus"} parsedArgs = DefaultParse(args, _baseDirectory) CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_UnableToOpenResourceFile1, Integer), errors.First().Code) Assert.Equal(2, errors.First().Arguments.Count()) args = {"/Win32Resource:\bogus"} parsedArgs = DefaultParse(args, _baseDirectory) CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_UnableToOpenResourceFile1, Integer), errors.First().Code) Assert.Equal(2, errors.First().Arguments.Count()) args = {"/win32manifest:goo.win32data:bar.win32data2"} parsedArgs = DefaultParse(args, _baseDirectory) CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_UnableToReadUacManifest2, Integer), errors.First().Code) Assert.Equal(2, errors.First().Arguments.Count()) args = {"/Win32icon:goo.win32data:bar.win32data2"} parsedArgs = DefaultParse(args, _baseDirectory) CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_UnableToOpenResourceFile1, Integer), errors.First().Code) Assert.Equal(2, errors.First().Arguments.Count()) args = {"/Win32Resource:goo.win32data:bar.win32data2"} parsedArgs = DefaultParse(args, _baseDirectory) CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_UnableToOpenResourceFile1, Integer), errors.First().Code) Assert.Equal(2, errors.First().Arguments.Count()) End Sub <Fact> Public Sub Win32IconContainsGarbage() Dim tmpFileName As String = Temp.CreateFile().WriteAllBytes(New Byte() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Path Dim parsedArgs = DefaultParse({"/win32icon:" + tmpFileName}, _baseDirectory) Dim compilation = CreateCompilationWithMscorlib40(New VisualBasicSyntaxTree() {}) Dim errors As IEnumerable(Of DiagnosticInfo) = Nothing CommonCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, errors) Assert.Equal(1, errors.Count()) Assert.Equal(DirectCast(ERRID.ERR_ErrorCreatingWin32ResourceFile, Integer), errors.First().Code) Assert.Equal(1, errors.First().Arguments.Count()) CleanupAllGeneratedFiles(tmpFileName) End Sub <WorkItem(217718, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=217718")> <Fact> Public Sub BadWin32Resource() Dim source = Temp.CreateFile(prefix:="", extension:=".vb").WriteAllText(" Module Test Sub Main() End Sub End Module").Path Dim badres = Temp.CreateFile().WriteAllBytes(New Byte() {0, 0}).Path Dim baseDir = Path.GetDirectoryName(source) Dim fileName = Path.GetFileName(source) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = New MockVisualBasicCompiler(Nothing, baseDir, { "/nologo", "/preferreduilang:en", "/win32resource:" + badres, source }).Run(outWriter) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC30136: Error creating Win32 resources: Unrecognized resource file format.", outWriter.ToString().Trim()) CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(badres) End Sub <Fact> Public Sub Win32ResourceOptions_Valid() CheckWin32ResourceOptions({"/win32resource:a"}, "a", Nothing, Nothing, False) CheckWin32ResourceOptions({"/win32icon:b"}, Nothing, "b", Nothing, False) CheckWin32ResourceOptions({"/win32manifest:c"}, Nothing, Nothing, "c", False) CheckWin32ResourceOptions({"/nowin32manifest"}, Nothing, Nothing, Nothing, True) End Sub <Fact> Public Sub Win32ResourceOptions_Empty() CheckWin32ResourceOptions({"/win32resource"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32resource", ":<file>")) CheckWin32ResourceOptions({"/win32resource:"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32resource", ":<file>")) CheckWin32ResourceOptions({"/win32resource: "}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32resource", ":<file>")) CheckWin32ResourceOptions({"/win32icon"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32icon", ":<file>")) CheckWin32ResourceOptions({"/win32icon:"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32icon", ":<file>")) CheckWin32ResourceOptions({"/win32icon: "}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32icon", ":<file>")) CheckWin32ResourceOptions({"/win32manifest"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32manifest", ":<file>")) CheckWin32ResourceOptions({"/win32manifest:"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32manifest", ":<file>")) CheckWin32ResourceOptions({"/win32manifest: "}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32manifest", ":<file>")) CheckWin32ResourceOptions({"/nowin32manifest"}, Nothing, Nothing, Nothing, True) CheckWin32ResourceOptions({"/nowin32manifest:"}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/nowin32manifest:")) CheckWin32ResourceOptions({"/nowin32manifest: "}, Nothing, Nothing, Nothing, False, Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/nowin32manifest:")) End Sub <Fact> Public Sub Win32ResourceOptions_Combinations() ' last occurrence wins CheckWin32ResourceOptions({"/win32resource:r", "/win32resource:s"}, "s", Nothing, Nothing, False) ' illegal CheckWin32ResourceOptions({"/win32resource:r", "/win32icon:i"}, "r", "i", Nothing, False, Diagnostic(ERRID.ERR_IconFileAndWin32ResFile)) ' documented as illegal, but works in dev10 CheckWin32ResourceOptions({"/win32resource:r", "/win32manifest:m"}, "r", Nothing, "m", False, Diagnostic(ERRID.ERR_CantHaveWin32ResAndManifest)) ' fine CheckWin32ResourceOptions({"/win32resource:r", "/nowin32manifest"}, "r", Nothing, Nothing, True) ' illegal CheckWin32ResourceOptions({"/win32icon:i", "/win32resource:r"}, "r", "i", Nothing, False, Diagnostic(ERRID.ERR_IconFileAndWin32ResFile)) ' last occurrence wins CheckWin32ResourceOptions({"/win32icon:i", "/win32icon:j"}, Nothing, "j", Nothing, False) ' fine CheckWin32ResourceOptions({"/win32icon:i", "/win32manifest:m"}, Nothing, "i", "m", False) ' fine CheckWin32ResourceOptions({"/win32icon:i", "/nowin32manifest"}, Nothing, "i", Nothing, True) ' documented as illegal, but works in dev10 CheckWin32ResourceOptions({"/win32manifest:m", "/win32resource:r"}, "r", Nothing, "m", False, Diagnostic(ERRID.ERR_CantHaveWin32ResAndManifest)) ' fine CheckWin32ResourceOptions({"/win32manifest:m", "/win32icon:i"}, Nothing, "i", "m", False) ' last occurrence wins CheckWin32ResourceOptions({"/win32manifest:m", "/win32manifest:n"}, Nothing, Nothing, "n", False) ' illegal CheckWin32ResourceOptions({"/win32manifest:m", "/nowin32manifest"}, Nothing, Nothing, "m", True, Diagnostic(ERRID.ERR_ConflictingManifestSwitches)) ' fine CheckWin32ResourceOptions({"/nowin32manifest", "/win32resource:r"}, "r", Nothing, Nothing, True) ' fine CheckWin32ResourceOptions({"/nowin32manifest", "/win32icon:i"}, Nothing, "i", Nothing, True) ' illegal CheckWin32ResourceOptions({"/nowin32manifest", "/win32manifest:m"}, Nothing, Nothing, "m", True, Diagnostic(ERRID.ERR_ConflictingManifestSwitches)) ' fine CheckWin32ResourceOptions({"/nowin32manifest", "/nowin32manifest"}, Nothing, Nothing, Nothing, True) End Sub <Fact> Public Sub Win32ResourceOptions_SimplyInvalid() Dim parsedArgs = DefaultParse({"/win32resource", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32resource", ":<file>")) parsedArgs = DefaultParse({"/win32resource+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/win32resource+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/win32resource-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/win32resource-")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/win32icon", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32icon", ":<file>")) parsedArgs = DefaultParse({"/win32icon+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/win32icon+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/win32icon-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/win32icon-")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/win32manifest", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("win32manifest", ":<file>")) parsedArgs = DefaultParse({"/win32manifest+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/win32manifest+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/win32manifest-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/win32manifest-")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub Private Sub CheckWin32ResourceOptions(args As String(), expectedResourceFile As String, expectedIcon As String, expectedManifest As String, expectedNoManifest As Boolean, ParamArray diags As DiagnosticDescription()) Dim parsedArgs = DefaultParse(args.Concat({"Test.vb"}), _baseDirectory) parsedArgs.Errors.Verify(diags) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(expectedResourceFile, parsedArgs.Win32ResourceFile) Assert.Equal(expectedIcon, parsedArgs.Win32Icon) Assert.Equal(expectedManifest, parsedArgs.Win32Manifest) Assert.Equal(expectedNoManifest, parsedArgs.NoWin32Manifest) End Sub <Fact> Public Sub ParseResourceDescription() Dim diags = New List(Of Diagnostic)() Dim desc As ResourceDescription desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someFile.goo.bar", desc.ResourceName) Assert.True(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,someName", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someName", desc.ResourceName) Assert.True(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,someName,public", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someName", desc.ResourceName) Assert.True(desc.IsPublic) ' use file name in place of missing resource name desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,,private", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someFile.goo.bar", desc.ResourceName) Assert.False(desc.IsPublic) ' quoted accessibility is fine desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,,""private""", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someFile.goo.bar", desc.ResourceName) Assert.False(desc.IsPublic) ' leading commas are ignored... desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", ",,\somepath\someFile.goo.bar,,private", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someFile.goo.bar", desc.ResourceName) Assert.False(desc.IsPublic) ' ...as long as there's no whitespace between them desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", ", ,\somepath\someFile.goo.bar,,private", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) ' trailing commas are ignored... desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,,private", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someFile.goo.bar", desc.ResourceName) Assert.False(desc.IsPublic) ' ...even if there's whitespace between them desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,,private, ,", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("someFile.goo.bar", desc.FileName) Assert.Equal("someFile.goo.bar", desc.ResourceName) Assert.False(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "\somepath\someFile.goo.bar,someName,publi", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", "publi")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "D:rive\relative\path,someName,public", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("D:rive\relative\path")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "inva\l*d?path,someName,public", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("inva\l*d?path")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", Nothing, _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("resource", ":<resinfo>")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("resource", ":<resinfo>")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " ", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " , ", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "path, ", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("path", desc.FileName) Assert.Equal("path", desc.ResourceName) Assert.True(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " ,name", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " , , ", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "path, , ", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " ,name, ", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " , ,private", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "path,name,", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("path", desc.FileName) Assert.Equal("name", desc.ResourceName) Assert.True(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "path,name,,", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("path", desc.FileName) Assert.Equal("name", desc.ResourceName) Assert.True(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "path,name, ", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", "path, ,private", _baseDirectory, diags, embedded:=False) diags.Verify() diags.Clear() Assert.Equal("path", desc.FileName) Assert.Equal("path", desc.ResourceName) Assert.False(desc.IsPublic) desc = VisualBasicCommandLineParser.ParseResourceDescription("resource", " ,name,private", _baseDirectory, diags, embedded:=False) diags.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("resource", " ")) diags.Clear() Assert.Null(desc) Dim longI = New String("i"c, 260) desc = VisualBasicCommandLineParser.ParseResourceDescription("", String.Format("{0},e,private", longI), _baseDirectory, diags, embedded:=False) ' // error BC2032: File name 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long diags.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii").WithLocation(1, 1)) End Sub <Fact> Public Sub ManagedResourceOptions() Dim parsedArgs As VisualBasicCommandLineArguments Dim resourceDescription As ResourceDescription parsedArgs = DefaultParse({"/resource:a", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.DisplayHelp) resourceDescription = parsedArgs.ManifestResources.Single() Assert.Null(resourceDescription.FileName) ' since embedded Assert.Equal("a", resourceDescription.ResourceName) parsedArgs = DefaultParse({"/res:b", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.DisplayHelp) resourceDescription = parsedArgs.ManifestResources.Single() Assert.Null(resourceDescription.FileName) ' since embedded Assert.Equal("b", resourceDescription.ResourceName) parsedArgs = DefaultParse({"/linkresource:c", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.DisplayHelp) resourceDescription = parsedArgs.ManifestResources.Single() Assert.Equal("c", resourceDescription.FileName) Assert.Equal("c", resourceDescription.ResourceName) parsedArgs = DefaultParse({"/linkres:d", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.DisplayHelp) resourceDescription = parsedArgs.ManifestResources.Single() Assert.Equal("d", resourceDescription.FileName) Assert.Equal("d", resourceDescription.ResourceName) End Sub <Fact> Public Sub ManagedResourceOptions_SimpleErrors() Dim parsedArgs = DefaultParse({"/resource:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("resource", ":<resinfo>")) parsedArgs = DefaultParse({"/resource: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("resource", ":<resinfo>")) parsedArgs = DefaultParse({"/resource", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("resource", ":<resinfo>")) parsedArgs = DefaultParse({"/RES+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/RES+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/res-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/res-:")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/linkresource:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("linkresource", ":<resinfo>")) parsedArgs = DefaultParse({"/linkresource: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("linkresource", ":<resinfo>")) parsedArgs = DefaultParse({"/linkresource", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("linkresource", ":<resinfo>")) parsedArgs = DefaultParse({"/linkRES+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/linkRES+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/linkres-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/linkres-:")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact> Public Sub ModuleManifest() Dim parsedArgs = DefaultParse({"/win32manifest:blah", "/target:module", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_IgnoreModuleManifest)) ' Illegal, but not clobbered. Assert.Equal("blah", parsedArgs.Win32Manifest) End Sub <Fact> Public Sub ArgumentParsing() Dim parsedArgs = InteractiveParse({"a + b"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(True, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"a + b; c"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(True, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"/help"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(True, parsedArgs.DisplayHelp) Assert.Equal(False, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"/version"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.True(parsedArgs.DisplayVersion) Assert.Equal(False, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"/version", "c"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.True(parsedArgs.DisplayVersion) Assert.Equal(True, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"/version:something"}, _baseDirectory) Assert.Equal(True, parsedArgs.Errors.Any()) Assert.False(parsedArgs.DisplayVersion) parsedArgs = InteractiveParse({"/?"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(True, parsedArgs.DisplayHelp) Assert.Equal(False, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"@dd"}, _baseDirectory) Assert.Equal(True, parsedArgs.Errors.Any()) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(False, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"c /define:DEBUG"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(True, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"\\"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".exe")) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(True, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"""/r d.dll"""}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(True, parsedArgs.SourceFiles.Any()) parsedArgs = InteractiveParse({"/r: d.dll"}, _baseDirectory) Assert.Equal(False, parsedArgs.Errors.Any()) Assert.Equal(False, parsedArgs.DisplayHelp) Assert.Equal(False, parsedArgs.SourceFiles.Any()) End Sub <Fact> Public Sub LangVersion() Dim parsedArgs = DefaultParse({"/langversion:9", "a.VB"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic9, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:9.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic9, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:10", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic10, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:10.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic10, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:11", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic11, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:11.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic11, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:12", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic12, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:12.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic12, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:14", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic14, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:14.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic14, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:15", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic15, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:15.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic15, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:15.3", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic15_3, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:15.5", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic15_5, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:16", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic16, parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:16.9", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic16_9, parsedArgs.ParseOptions.LanguageVersion) ' The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary() parsedArgs = DefaultParse({"/langVERSION:default", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion) Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:latest", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.Latest, parsedArgs.ParseOptions.SpecifiedLanguageVersion) Assert.Equal(LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) ' default: "current version" parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) ' overriding parsedArgs = DefaultParse({"/langVERSION:10", "/langVERSION:9.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(LanguageVersion.VisualBasic9, parsedArgs.ParseOptions.LanguageVersion) ' errors parsedArgs = DefaultParse({"/langVERSION", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("langversion", ":<number>")) Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/langVERSION+")) ' TODO: Dev11 reports ERR_ArgumentRequired Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("langversion", ":<number>")) Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:8", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("langversion", "8")) Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) parsedArgs = DefaultParse({"/langVERSION:" & (LanguageVersion.VisualBasic12 + 1), "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("langversion", CStr(LanguageVersion.VisualBasic12 + 1))) Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), parsedArgs.ParseOptions.LanguageVersion) End Sub <Fact> Public Sub DelaySign() Dim parsedArgs = DefaultParse({"/delaysign", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.NotNull(parsedArgs.CompilationOptions.DelaySign) Assert.Equal(True, parsedArgs.CompilationOptions.DelaySign) parsedArgs = DefaultParse({"/delaysign+", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.NotNull(parsedArgs.CompilationOptions.DelaySign) Assert.Equal(True, parsedArgs.CompilationOptions.DelaySign) parsedArgs = DefaultParse({"/DELAYsign-", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.NotNull(parsedArgs.CompilationOptions.DelaySign) Assert.Equal(False, parsedArgs.CompilationOptions.DelaySign) parsedArgs = DefaultParse({"/delaysign:-", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("delaysign")) parsedArgs = InteractiveParse({"/d:a=1"}, _baseDirectory) ' test default value parsedArgs.Errors.Verify() Assert.Null(parsedArgs.CompilationOptions.DelaySign) End Sub <WorkItem(546113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546113")> <Fact> Public Sub OutputVerbose() Dim parsedArgs = DefaultParse({"/verbose", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Verbose, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/verbose+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Verbose, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/verbose-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Normal, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/VERBOSE:-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/VERBOSE:-")) parsedArgs = DefaultParse({"/verbose-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("verbose")) parsedArgs = DefaultParse({"/verbose+:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("verbose")) parsedArgs = DefaultParse({"/verbOSE:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/verbOSE:")) parsedArgs = InteractiveParse({"/d:a=1"}, _baseDirectory) ' test default value parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Normal, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/quiet", "/verbose", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Verbose, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/quiet", "/verbose-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Normal, parsedArgs.OutputLevel) End Sub <WorkItem(546113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546113")> <Fact> Public Sub OutputQuiet() Dim parsedArgs = DefaultParse({"/quiet", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Quiet, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/quiet+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Quiet, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/quiet-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Normal, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/QUIET:-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/QUIET:-")) parsedArgs = DefaultParse({"/quiet-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("quiet")) parsedArgs = DefaultParse({"/quiet+:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("quiet")) parsedArgs = DefaultParse({"/quiET:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/quiET:")) parsedArgs = InteractiveParse({"/d:a=1"}, _baseDirectory) ' test default value parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Normal, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/verbose", "/quiet", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Quiet, parsedArgs.OutputLevel) parsedArgs = DefaultParse({"/verbose", "/quiet-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputLevel.Normal, parsedArgs.OutputLevel) End Sub <Fact> Public Sub Optimize() Dim parsedArgs = DefaultParse({"/optimize", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel) parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel) ' default parsedArgs = DefaultParse({"/OPTIMIZE+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel) parsedArgs = DefaultParse({"/optimize-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel) parsedArgs = DefaultParse({"/optimize-", "/optimize+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel) parsedArgs = DefaultParse({"/OPTIMIZE:", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optimize")) parsedArgs = DefaultParse({"/OPTIMIZE+:", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optimize")) parsedArgs = DefaultParse({"/optimize-:", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optimize")) End Sub <WorkItem(5417, "DevDiv")> <Fact> Public Sub Deterministic() Dim ParsedArgs = DefaultParse({"a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.Equal(False, ParsedArgs.CompilationOptions.Deterministic) ParsedArgs = DefaultParse({"/deterministic+", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.Equal(True, ParsedArgs.CompilationOptions.Deterministic) ParsedArgs = DefaultParse({"/deterministic", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.Equal(True, ParsedArgs.CompilationOptions.Deterministic) ParsedArgs = DefaultParse({"/DETERMINISTIC+", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.Equal(True, ParsedArgs.CompilationOptions.Deterministic) ParsedArgs = DefaultParse({"/deterministic-", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.Equal(False, ParsedArgs.CompilationOptions.Deterministic) End Sub <WorkItem(546301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546301")> <Fact> Public Sub Parallel() Dim parsedArgs = DefaultParse({"/parallel", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/p", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) ' default parsedArgs = DefaultParse({"/PARALLEL+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/PARALLEL-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/PArallel-", "/PArallel+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/parallel:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("parallel")) parsedArgs = DefaultParse({"/parallel+:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("parallel")) parsedArgs = DefaultParse({"/parallel-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("parallel")) parsedArgs = DefaultParse({"/P+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/P-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/P-", "/P+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.ConcurrentBuild) parsedArgs = DefaultParse({"/p:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("p")) parsedArgs = DefaultParse({"/p+:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("p")) parsedArgs = DefaultParse({"/p-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("p")) End Sub <Fact> Public Sub SubsystemVersionTests() Dim parsedArgs = DefaultParse({"/subsystemversion:4.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(SubsystemVersion.Create(4, 0), parsedArgs.EmitOptions.SubsystemVersion) ' wrongly supported subsystem version. CompilationOptions data will be faithful to the user input. ' It is normalized at the time of emit. parsedArgs = DefaultParse({"/subsystemversion:0.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() ' no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion) parsedArgs = DefaultParse({"/subsystemversion:0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() ' no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion) parsedArgs = DefaultParse({"/subsystemversion:3.99", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() ' no warning in Dev11 Assert.Equal(SubsystemVersion.Create(3, 99), parsedArgs.EmitOptions.SubsystemVersion) parsedArgs = DefaultParse({"/subsystemversion:4.0", "/subsystemversion:5.333", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(SubsystemVersion.Create(5, 333), parsedArgs.EmitOptions.SubsystemVersion) parsedArgs = DefaultParse({"/subsystemversion:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("subsystemversion", ":<version>")) parsedArgs = DefaultParse({"/subsystemversion", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("subsystemversion", ":<version>")) parsedArgs = DefaultParse({"/subsystemversion-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/subsystemversion-")) ' TODO: Dev11 reports ERRID.ERR_ArgumentRequired parsedArgs = DefaultParse({"/subsystemversion: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("subsystemversion", ":<version>")) parsedArgs = DefaultParse({"/subsystemversion: 4.1", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments(" 4.1")) parsedArgs = DefaultParse({"/subsystemversion:4 .0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("4 .0")) parsedArgs = DefaultParse({"/subsystemversion:4. 0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("4. 0")) parsedArgs = DefaultParse({"/subsystemversion:.", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments(".")) parsedArgs = DefaultParse({"/subsystemversion:4.", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("4.")) parsedArgs = DefaultParse({"/subsystemversion:.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments(".0")) parsedArgs = DefaultParse({"/subsystemversion:4.2 ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/subsystemversion:4.65536", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("4.65536")) parsedArgs = DefaultParse({"/subsystemversion:65536.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("65536.0")) parsedArgs = DefaultParse({"/subsystemversion:-4.0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("-4.0")) ' TODO: incompatibilities: versions lower than '6.2' and 'arm', 'winmdobj', 'appcontainer' End Sub <Fact> Public Sub Codepage() Dim parsedArgs = DefaultParse({"/CodePage:1200", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("Unicode", parsedArgs.Encoding.EncodingName) parsedArgs = DefaultParse({"/CodePage:1200", "/CodePage:65001", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("Unicode (UTF-8)", parsedArgs.Encoding.EncodingName) ' errors parsedArgs = DefaultParse({"/codepage:0", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadCodepage).WithArguments("0")) parsedArgs = DefaultParse({"/codepage:abc", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadCodepage).WithArguments("abc")) parsedArgs = DefaultParse({"/codepage:-5", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadCodepage).WithArguments("-5")) parsedArgs = DefaultParse({"/codepage: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("codepage", ":<number>")) parsedArgs = DefaultParse({"/codepage:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("codepage", ":<number>")) parsedArgs = DefaultParse({"/codepage+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/codepage+")) ' Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/codepage", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("codepage", ":<number>")) End Sub <Fact, WorkItem(24735, "https://github.com/dotnet/roslyn/issues/24735")> Public Sub ChecksumAlgorithm() Dim parsedArgs As VisualBasicCommandLineArguments parsedArgs = DefaultParse({"/checksumAlgorithm:sHa1", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(SourceHashAlgorithm.Sha1, parsedArgs.ChecksumAlgorithm) Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm) parsedArgs = DefaultParse({"/checksumAlgorithm:sha256", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm) Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm) parsedArgs = DefaultParse({"a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm) Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm) ' error parsedArgs = DefaultParse({"/checksumAlgorithm:256", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadChecksumAlgorithm).WithArguments("256")) parsedArgs = DefaultParse({"/checksumAlgorithm:sha-1", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadChecksumAlgorithm).WithArguments("sha-1")) parsedArgs = DefaultParse({"/checksumAlgorithm:sha", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadChecksumAlgorithm).WithArguments("sha")) parsedArgs = DefaultParse({"/checksumAlgorithm: ", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("checksumalgorithm", ":<algorithm>")) parsedArgs = DefaultParse({"/checksumAlgorithm:", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("checksumalgorithm", ":<algorithm>")) parsedArgs = DefaultParse({"/checksumAlgorithm", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("checksumalgorithm", ":<algorithm>")) parsedArgs = DefaultParse({"/checksumAlgorithm+", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/checksumAlgorithm+")) End Sub <Fact> Public Sub MainTypeName() Dim parsedArgs = DefaultParse({"/main:A.B.C", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("A.B.C", parsedArgs.CompilationOptions.MainTypeName) ' overriding the value parsedArgs = DefaultParse({"/Main:A.B.C", "/M:X.Y.Z", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("X.Y.Z", parsedArgs.CompilationOptions.MainTypeName) parsedArgs = DefaultParse({"/MAIN: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("main", ":<class>")) Assert.Null(parsedArgs.CompilationOptions.MainTypeName) ' EDMAURER Dev11 accepts and MainTypeName is " " ' errors parsedArgs = DefaultParse({"/maiN:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("main", ":<class>")) parsedArgs = DefaultParse({"/m", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("m", ":<class>")) parsedArgs = DefaultParse({"/m+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/m+")) ' Dev11 reports ERR_ArgumentRequired ' incompatibilities ignored by Dev11 parsedArgs = DefaultParse({"/MAIN:XYZ", "/t:library", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("XYZ", parsedArgs.CompilationOptions.MainTypeName) Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/MAIN:XYZ", "/t:module", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind) End Sub <Fact> Public Sub OptionCompare() Dim parsedArgs = InteractiveParse({"/optioncompare"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Length) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("optioncompare", ":binary|text")) Assert.Equal(False, parsedArgs.CompilationOptions.OptionCompareText) parsedArgs = InteractiveParse({"/optioncompare:text", "/optioncompare"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Length) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("optioncompare", ":binary|text")) Assert.Equal(True, parsedArgs.CompilationOptions.OptionCompareText) parsedArgs = InteractiveParse({"/opTioncompare:Text", "/optioncomparE:bINARY"}, _baseDirectory) Assert.Equal(0, parsedArgs.Errors.Length) Assert.Equal(False, parsedArgs.CompilationOptions.OptionCompareText) parsedArgs = InteractiveParse({"/d:a=1"}, _baseDirectory) ' test default value Assert.Equal(0, parsedArgs.Errors.Length) Assert.Equal(False, parsedArgs.CompilationOptions.OptionCompareText) End Sub <Fact> Public Sub OptionExplicit() Dim parsedArgs = InteractiveParse({"/optiONexplicit"}, _baseDirectory) Assert.Equal(0, parsedArgs.Errors.Length) Assert.Equal(True, parsedArgs.CompilationOptions.OptionExplicit) parsedArgs = InteractiveParse({"/optiONexplicit:+"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Length) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optionexplicit")) Assert.Equal(True, parsedArgs.CompilationOptions.OptionExplicit) parsedArgs = InteractiveParse({"/optiONexplicit-:"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Length) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optionexplicit")) parsedArgs = InteractiveParse({"/optionexplicit+", "/optiONexplicit-:"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Length) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optionexplicit")) parsedArgs = InteractiveParse({"/optionexplicit+", "/optiONexplicit-", "/optiONexpliCIT+"}, _baseDirectory) Assert.Equal(0, parsedArgs.Errors.Length) Assert.Equal(True, parsedArgs.CompilationOptions.OptionExplicit) parsedArgs = InteractiveParse({"/d:a=1"}, _baseDirectory) ' test default value Assert.Equal(0, parsedArgs.Errors.Length) Assert.Equal(True, parsedArgs.CompilationOptions.OptionExplicit) End Sub <Fact> Public Sub OptionInfer() Dim parsedArgs = InteractiveParse({"/optiONinfer"}, _baseDirectory) Assert.Equal(0, parsedArgs.Errors.Length) Assert.Equal(True, parsedArgs.CompilationOptions.OptionInfer) parsedArgs = InteractiveParse({"/OptionInfer:+"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optioninfer")) parsedArgs = InteractiveParse({"/OPTIONinfer-:"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optioninfer")) parsedArgs = InteractiveParse({"/optioninfer+", "/optioninFER-:"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("optioninfer")) parsedArgs = InteractiveParse({"/optioninfer+", "/optioninfeR-", "/OptionInfer+"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.CompilationOptions.OptionInfer) parsedArgs = InteractiveParse({"/d:a=1"}, _baseDirectory) ' test default value parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.CompilationOptions.OptionInfer) End Sub Private ReadOnly s_VBC_VER As Double = PredefinedPreprocessorSymbols.CurrentVersionNumber <Fact> Public Sub LanguageVersionAdded_Canary() ' When a new version is added, this test will break. This list must be checked: ' - update the "UpgradeProject" codefixer (not yet supported in VB) ' - update all the tests that call this canary ' - update the command-line documentation (CommandLine.md) AssertEx.SetEqual({"default", "9", "10", "11", "12", "14", "15", "15.3", "15.5", "16", "16.9", "latest"}, System.Enum.GetValues(GetType(LanguageVersion)).Cast(Of LanguageVersion)().Select(Function(v) v.ToDisplayString())) ' For minor versions, the format should be "x.y", such as "15.3" End Sub <Fact> Public Sub LanguageVersion_GetErrorCode() Dim versions = System.Enum.GetValues(GetType(LanguageVersion)). Cast(Of LanguageVersion)(). Except({LanguageVersion.Default, LanguageVersion.Latest}). Select(Function(v) v.GetErrorName()) Dim errorCodes = { "9.0", "10.0", "11.0", "12.0", "14.0", "15.0", "15.3", "15.5", "16", "16.9" } AssertEx.SetEqual(versions, errorCodes) ' The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary() End Sub <Fact> Public Sub LanguageVersion_MapSpecifiedToEffectiveVersion() Assert.Equal(LanguageVersion.VisualBasic9, LanguageVersion.VisualBasic9.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic10, LanguageVersion.VisualBasic10.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic11, LanguageVersion.VisualBasic11.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic12, LanguageVersion.VisualBasic12.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic14, LanguageVersion.VisualBasic14.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic15, LanguageVersion.VisualBasic15.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic15_3, LanguageVersion.VisualBasic15_3.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic15_5, LanguageVersion.VisualBasic15_5.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic16, LanguageVersion.VisualBasic16.MapSpecifiedToEffectiveVersion()) Assert.Equal(LanguageVersion.VisualBasic16_9, LanguageVersion.VisualBasic16_9.MapSpecifiedToEffectiveVersion()) ' The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary() End Sub <Theory, InlineData("9", True, LanguageVersion.VisualBasic9), InlineData("9.0", True, LanguageVersion.VisualBasic9), InlineData("10", True, LanguageVersion.VisualBasic10), InlineData("10.0", True, LanguageVersion.VisualBasic10), InlineData("11", True, LanguageVersion.VisualBasic11), InlineData("11.0", True, LanguageVersion.VisualBasic11), InlineData("12", True, LanguageVersion.VisualBasic12), InlineData("12.0", True, LanguageVersion.VisualBasic12), InlineData("14", True, LanguageVersion.VisualBasic14), InlineData("14.0", True, LanguageVersion.VisualBasic14), InlineData("15", True, LanguageVersion.VisualBasic15), InlineData("15.0", True, LanguageVersion.VisualBasic15), InlineData("15.3", True, LanguageVersion.VisualBasic15_3), InlineData("15.5", True, LanguageVersion.VisualBasic15_5), InlineData("16", True, LanguageVersion.VisualBasic16), InlineData("16.0", True, LanguageVersion.VisualBasic16), InlineData("16.9", True, LanguageVersion.VisualBasic16_9), InlineData("DEFAULT", True, LanguageVersion.Default), InlineData("default", True, LanguageVersion.Default), InlineData("LATEST", True, LanguageVersion.Latest), InlineData("latest", True, LanguageVersion.Latest), InlineData(Nothing, False, LanguageVersion.Default), InlineData("bad", False, LanguageVersion.Default)> Public Sub LanguageVersion_TryParseDisplayString(input As String, success As Boolean, expected As LanguageVersion) Dim version As LanguageVersion Assert.Equal(success, TryParse(input, version)) Assert.Equal(expected, version) ' The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary() End Sub <Fact> Public Sub LanguageVersion_ListLangVersions() Dim dir = Temp.CreateDirectory() Dim outWriter As New StringWriter() Dim exitCode As Integer = New MockVisualBasicCompiler(Nothing, dir.ToString(), {"/langversion:?"}).Run(outWriter, Nothing) Assert.Equal(0, exitCode) Dim actual = outWriter.ToString() Dim expected = [Enum].GetValues(GetType(LanguageVersion)).Cast(Of LanguageVersion)().Select(Function(v) v.ToDisplayString()) Dim acceptableSurroundingChar = {CChar(vbCr), CChar(vbLf), "("c, ")"c, " "c} For Each v In expected Dim foundIndex = actual.IndexOf(v) Assert.True(foundIndex > 0, $"Missing version '{v}'") Assert.True(Array.IndexOf(acceptableSurroundingChar, actual(foundIndex - 1)) >= 0) Assert.True(Array.IndexOf(acceptableSurroundingChar, actual(foundIndex + v.Length)) >= 0) Next End Sub <Fact> Public Sub TestDefine() TestDefines({"/D:a=True,b=1", "a.vb"}, {"a", True}, {"b", 1}, {"TARGET", "exe"}, {"VBC_VER", s_VBC_VER}) TestDefines({"/D:a=True,b=1", "/define:a=""123"",b=False", "a.vb"}, {"a", "123"}, {"b", False}, {"TARGET", "exe"}, {"VBC_VER", s_VBC_VER}) TestDefines({"/D:a=""\\\\a"",b=""\\\\\b""", "a.vb"}, {"a", "\\\\a"}, {"b", "\\\\\b"}, {"TARGET", "exe"}, {"VBC_VER", s_VBC_VER}) TestDefines({"/define:DEBUG", "a.vb"}, {"DEBUG", True}, {"TARGET", "exe"}, {"VBC_VER", s_VBC_VER}) TestDefines({"/D:TARGET=True,VBC_VER=1", "a.vb"}, {"TARGET", True}, {"VBC_VER", 1}) End Sub Private Sub TestDefines(args As IEnumerable(Of String), ParamArray symbols As Object()()) Dim parsedArgs = DefaultParse(args, _baseDirectory) Assert.False(parsedArgs.Errors.Any) Assert.Equal(symbols.Length, parsedArgs.ParseOptions.PreprocessorSymbols.Length) Dim sortedDefines = parsedArgs.ParseOptions. PreprocessorSymbols.Select( Function(d) New With {d.Key, d.Value}).OrderBy(Function(o) o.Key) For i = 0 To symbols.Length - 1 Assert.Equal(symbols(i)(0), sortedDefines(i).Key) Assert.Equal(symbols(i)(1), sortedDefines(i).Value) Next End Sub <Fact> Public Sub OptionStrict() Dim parsedArgs = DefaultParse({"/optionStrict", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(VisualBasic.OptionStrict.On, parsedArgs.CompilationOptions.OptionStrict) parsedArgs = DefaultParse({"/optionStrict+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(VisualBasic.OptionStrict.On, parsedArgs.CompilationOptions.OptionStrict) parsedArgs = DefaultParse({"/optionStrict-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(VisualBasic.OptionStrict.Off, parsedArgs.CompilationOptions.OptionStrict) parsedArgs = DefaultParse({"/OptionStrict:cusTom", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(VisualBasic.OptionStrict.Custom, parsedArgs.CompilationOptions.OptionStrict) parsedArgs = DefaultParse({"/OptionStrict:cusTom", "/optionstrict-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(VisualBasic.OptionStrict.Off, parsedArgs.CompilationOptions.OptionStrict) parsedArgs = DefaultParse({"/optionstrict-", "/OptionStrict:cusTom", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(VisualBasic.OptionStrict.Custom, parsedArgs.CompilationOptions.OptionStrict) parsedArgs = DefaultParse({"/optionstrict:", "/OptionStrict:cusTom", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("optionstrict", ":custom")) parsedArgs = DefaultParse({"/optionstrict:xxx", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("optionstrict", ":custom")) End Sub <WorkItem(546319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546319")> <WorkItem(546318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546318")> <WorkItem(685392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685392")> <Fact> Public Sub RootNamespace() Dim parsedArgs = DefaultParse({"/rootnamespace:One.Two.Three", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("One.Two.Three", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace:One Two Three", "/rootnamespace:One.Two.Three", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("One.Two.Three", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace:""One.Two.Three""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("One.Two.Three", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("rootnamespace", ":<string>")) parsedArgs = DefaultParse({"/rootnamespace:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("rootnamespace", ":<string>")) parsedArgs = DefaultParse({"/rootnamespace+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/rootnamespace+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/rootnamespace-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/rootnamespace-:")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/rootnamespace:+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("+")) parsedArgs = DefaultParse({"/rootnamespace: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("rootnamespace", ":<string>")) parsedArgs = DefaultParse({"/rootnamespace: A.B.C", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments(" A.B.C")) parsedArgs = DefaultParse({"/rootnamespace:[abcdef", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("[abcdef")) parsedArgs = DefaultParse({"/rootnamespace:abcdef]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("abcdef]")) parsedArgs = DefaultParse({"/rootnamespace:[[abcdef]]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("[[abcdef]]")) parsedArgs = DefaultParse({"/rootnamespace:[global]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("[global]", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace:goo.[global].bar", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("goo.[global].bar", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace:goo.[bar]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("goo.[bar]", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace:goo$", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("goo$")) parsedArgs = DefaultParse({"/rootnamespace:I(", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("I(")) parsedArgs = DefaultParse({"/rootnamespace:_", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("_")) parsedArgs = DefaultParse({"/rootnamespace:[_]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("[_]")) parsedArgs = DefaultParse({"/rootnamespace:__.___", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("__.___", parsedArgs.CompilationOptions.RootNamespace) parsedArgs = DefaultParse({"/rootnamespace:[", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("[")) parsedArgs = DefaultParse({"/rootnamespace:]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("]")) parsedArgs = DefaultParse({"/rootnamespace:[]", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_BadNamespaceName1).WithArguments("[]")) End Sub <Fact> Public Sub Link_SimpleTests() Dim parsedArgs = DefaultParse({"/link:a", "/link:b,,,,c", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal({"a", "b", "c"}, parsedArgs.MetadataReferences. Where(Function(res) res.Properties.EmbedInteropTypes). Select(Function(res) res.Reference)) parsedArgs = DefaultParse({"/Link: ,,, b ,,", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal({" ", " b "}, parsedArgs.MetadataReferences. Where(Function(res) res.Properties.EmbedInteropTypes). Select(Function(res) res.Reference)) parsedArgs = DefaultParse({"/l:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("l", ":<file_list>")) parsedArgs = DefaultParse({"/L", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("l", ":<file_list>")) parsedArgs = DefaultParse({"/l+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/l+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/link-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/link-:")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact> Public Sub Recurse_SimpleTests() Dim dir = Temp.CreateDirectory() Dim file1 = dir.CreateFile("a.vb") Dim file2 = dir.CreateFile("b.vb") Dim file3 = dir.CreateFile("c.txt") Dim file4 = dir.CreateDirectory("d1").CreateFile("d.txt") Dim file5 = dir.CreateDirectory("d2").CreateFile("e.vb") file1.WriteAllText("") file2.WriteAllText("") file3.WriteAllText("") file4.WriteAllText("") file5.WriteAllText("") Dim parsedArgs = DefaultParse({"/recurse:" & dir.ToString() & "\*.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal({"{DIR}\a.vb", "{DIR}\b.vb", "{DIR}\d2\e.vb"}, parsedArgs.SourceFiles.Select(Function(file) file.Path.Replace(dir.ToString(), "{DIR}"))) parsedArgs = DefaultParse({"*.vb"}, dir.ToString()) parsedArgs.Errors.Verify() AssertEx.Equal({"{DIR}\a.vb", "{DIR}\b.vb"}, parsedArgs.SourceFiles.Select(Function(file) file.Path.Replace(dir.ToString(), "{DIR}"))) parsedArgs = DefaultParse({"/reCURSE:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("recurse", ":<wildcard>")) parsedArgs = DefaultParse({"/RECURSE: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("recurse", ":<wildcard>")) parsedArgs = DefaultParse({"/recurse", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("recurse", ":<wildcard>")) parsedArgs = DefaultParse({"/recurse+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/recurse+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/recurse-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/recurse-:")) ' TODO: Dev11 reports ERR_ArgumentRequired CleanupAllGeneratedFiles(file1.Path) CleanupAllGeneratedFiles(file2.Path) CleanupAllGeneratedFiles(file3.Path) CleanupAllGeneratedFiles(file4.Path) CleanupAllGeneratedFiles(file5.Path) End Sub <WorkItem(545991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545991")> <WorkItem(546009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546009")> <Fact> Public Sub Recurse_SimpleTests2() Dim folder = Temp.CreateDirectory() Dim file1 = folder.CreateFile("a.cs") Dim file2 = folder.CreateFile("b.vb") Dim file3 = folder.CreateFile("c.cpp") Dim file4 = folder.CreateDirectory("A").CreateFile("A_d.txt") Dim file5 = folder.CreateDirectory("B").CreateFile("B_e.vb") Dim file6 = folder.CreateDirectory("C").CreateFile("B_f.cs") file1.WriteAllText("") file2.WriteAllText("") file3.WriteAllText("") file4.WriteAllText("") file5.WriteAllText("") file6.WriteAllText("") Dim outWriter As New StringWriter() Dim exitCode As Integer = New MockVisualBasicCompiler(Nothing, folder.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/recurse:.", "b.vb", "/out:abc.dll"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2014: the value '.' is invalid for option 'recurse'", outWriter.ToString().Trim()) outWriter = New StringWriter() exitCode = New MockVisualBasicCompiler(Nothing, folder.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/recurse:. ", "b.vb", "/out:abc.dll"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2014: the value '.' is invalid for option 'recurse'", outWriter.ToString().Trim()) outWriter = New StringWriter() exitCode = New MockVisualBasicCompiler(Nothing, folder.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/recurse: . ", "/out:abc.dll"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2014: the value ' .' is invalid for option 'recurse'|vbc : error BC2008: no input sources specified", outWriter.ToString().Trim().Replace(vbCrLf, "|")) outWriter = New StringWriter() exitCode = New MockVisualBasicCompiler(Nothing, folder.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/recurse:./.", "/out:abc.dll"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2014: the value './.' is invalid for option 'recurse'|vbc : error BC2008: no input sources specified", outWriter.ToString().Trim().Replace(vbCrLf, "|")) Dim args As VisualBasicCommandLineArguments Dim resolvedSourceFiles As String() args = DefaultParse({"/recurse:*.cp*", "/recurse:b\*.v*", "/out:a.dll"}, folder.Path) args.Errors.Verify() resolvedSourceFiles = args.SourceFiles.Select(Function(f) f.Path).ToArray() AssertEx.Equal({folder.Path + "\c.cpp", folder.Path + "\b\B_e.vb"}, resolvedSourceFiles) args = DefaultParse({"/recurse:.\\\\\\*.vb", "/out:a.dll"}, folder.Path) args.Errors.Verify() resolvedSourceFiles = args.SourceFiles.Select(Function(f) f.Path).ToArray() Assert.Equal(2, resolvedSourceFiles.Length) args = DefaultParse({"/recurse:.////*.vb", "/out:a.dll"}, folder.Path) args.Errors.Verify() resolvedSourceFiles = args.SourceFiles.Select(Function(f) f.Path).ToArray() Assert.Equal(2, resolvedSourceFiles.Length) CleanupAllGeneratedFiles(file1.Path) CleanupAllGeneratedFiles(file2.Path) CleanupAllGeneratedFiles(file3.Path) CleanupAllGeneratedFiles(file4.Path) CleanupAllGeneratedFiles(file5.Path) CleanupAllGeneratedFiles(file6.Path) End Sub <WorkItem(948285, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948285")> <Fact> Public Sub Recurse_SimpleTests3() Dim folder = Temp.CreateDirectory() Dim outWriter = New StringWriter() Dim exitCode = New MockVisualBasicCompiler(Nothing, folder.Path, {"/nologo", "/preferreduilang:en", "/t:exe", "/out:abc.exe"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2008: no input sources specified", outWriter.ToString().Trim().Replace(vbCrLf, "|")) End Sub <Fact> Public Sub Reference_SimpleTests() Dim parsedArgs = DefaultParse({"/nostdlib", "/vbruntime-", "/r:a", "/REFERENCE:b,,,,c", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal({"a", "b", "c"}, parsedArgs.MetadataReferences. Where(Function(res) Not res.Properties.EmbedInteropTypes AndAlso Not res.Reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)). Select(Function(res) res.Reference)) parsedArgs = DefaultParse({"/Reference: ,,, b ,,", "/nostdlib", "/vbruntime-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal({" ", " b "}, parsedArgs.MetadataReferences. Where(Function(res) Not res.Properties.EmbedInteropTypes AndAlso Not res.Reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)). Select(Function(res) res.Reference)) parsedArgs = DefaultParse({"/r:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("r", ":<file_list>")) parsedArgs = DefaultParse({"/R", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("r", ":<file_list>")) parsedArgs = DefaultParse({"/reference+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/reference+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/reference-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/reference-:")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub Private Class SimpleMetadataResolver Inherits MetadataReferenceResolver Private ReadOnly _pathResolver As RelativePathResolver Public Sub New(baseDirectory As String) _pathResolver = New RelativePathResolver(ImmutableArray(Of String).Empty, baseDirectory) End Sub Public Overrides Function ResolveReference(reference As String, baseFilePath As String, properties As MetadataReferenceProperties) As ImmutableArray(Of PortableExecutableReference) Dim resolvedPath = _pathResolver.ResolvePath(reference, baseFilePath) If resolvedPath Is Nothing OrElse Not File.Exists(reference) Then Return Nothing End If Return ImmutableArray.Create(MetadataReference.CreateFromFile(resolvedPath, properties)) End Function Public Overrides Function Equals(other As Object) As Boolean Return True End Function Public Overrides Function GetHashCode() As Integer Return 1 End Function End Class <Fact> Public Sub Reference_CorLibraryAddedWhenThereAreUnresolvedReferences() Dim parsedArgs = DefaultParse({"/r:unresolved", "a.vb"}, _baseDirectory) Dim metadataResolver = New SimpleMetadataResolver(_baseDirectory) Dim references = parsedArgs.ResolveMetadataReferences(metadataResolver).ToImmutableArray() Assert.Equal(4, references.Length) Assert.Contains(references, Function(r) r.IsUnresolved) Assert.Contains(references, Function(r) Dim peRef = TryCast(r, PortableExecutableReference) Return peRef IsNot Nothing AndAlso peRef.FilePath.EndsWith("mscorlib.dll", StringComparison.Ordinal) End Function) End Sub <Fact> Public Sub Reference_CorLibraryAddedWhenThereAreNoUnresolvedReferences() Dim parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) Dim metadataResolver = New SimpleMetadataResolver(_baseDirectory) Dim references = parsedArgs.ResolveMetadataReferences(metadataResolver).ToImmutableArray() Assert.Equal(3, references.Length) Assert.DoesNotContain(references, Function(r) r.IsUnresolved) Assert.Contains(references, Function(r) Dim peRef = TryCast(r, PortableExecutableReference) Return peRef IsNot Nothing AndAlso peRef.FilePath.EndsWith("mscorlib.dll", StringComparison.Ordinal) End Function) End Sub <Fact> Public Sub ParseAnalyzers() Dim parsedArgs = DefaultParse({"/a:goo.dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(1, parsedArgs.AnalyzerReferences.Length) Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences(0).FilePath) parsedArgs = DefaultParse({"/analyzer:goo.dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(1, parsedArgs.AnalyzerReferences.Length) Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences(0).FilePath) parsedArgs = DefaultParse({"/analyzer:""goo.dll""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(1, parsedArgs.AnalyzerReferences.Length) Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences(0).FilePath) parsedArgs = DefaultParse({"/a:goo.dll,bar.dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(2, parsedArgs.AnalyzerReferences.Length) Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences(0).FilePath) Assert.Equal("bar.dll", parsedArgs.AnalyzerReferences(1).FilePath) parsedArgs = DefaultParse({"/a:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("a", ":<file_list>")) parsedArgs = DefaultParse({"/a", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("a", ":<file_list>")) End Sub <Fact> Public Sub Analyzers_Missing() Dim source = "Imports System" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/a:missing.dll", "a.vb"}) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2017: could not find library 'missing.dll'", outWriter.ToString().Trim()) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub Analyzers_Empty() Dim source = "Imports System" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/a:" + GetType(Object).Assembly.Location, "a.vb"}) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) Assert.DoesNotContain("warning", outWriter.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub Analyzers_Found() Dim source = "Imports System " + vbCrLf + "Public Class Tester" + vbCrLf + "End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' This assembly has a MockDiagnosticAnalyzer type which should get run by this compilation. Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb"}) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) ' Diagnostic cannot instantiate Assert.True(outWriter.ToString().Contains("warning BC42376")) ' Diagnostic is thrown Assert.True(outWriter.ToString().Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared")) Assert.True(outWriter.ToString().Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared")) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub Analyzers_WithRuleSet() Dim source = "Imports System " + vbCrLf + "Public Class Tester" + vbCrLf + "End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim rulesetSource = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed"> <Rule Id="Warning01" Action="Error"/> <Rule Id="Test02" Action="Warning"/> <Rule Id="Warning03" Action="None"/> </Rules> </RuleSet> Dim ruleSetFile = CreateRuleSetFile(rulesetSource) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb", "/ruleset:" + ruleSetFile.Path}) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) ' Diagnostic cannot instantiate Assert.True(outWriter.ToString().Contains("warning BC42376")) '' Diagnostic thrown as error 'Assert.True(outWriter.ToString().Contains("error Warning01")) ' Diagnostic is suppressed Assert.False(outWriter.ToString().Contains("warning Warning03")) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub Analyzers_CommandLineOverridesRuleset1() Dim source = "Imports System " + vbCrLf + "Public Class Tester" + vbCrLf + "End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim rulesetSource = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <IncludeAll Action="Warning"/> </RuleSet> Dim ruleSetFile = CreateRuleSetFile(rulesetSource) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/preferreduilang:en", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb", "/ruleset:" & ruleSetFile.Path, "/warnaserror", "/nowarn:42376" }) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) ' Diagnostics thrown as error: command line always overrides ruleset. Dim output = outWriter.ToString() Assert.Contains("error Warning01", output, StringComparison.Ordinal) Assert.Contains("error Warning03", output, StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) vbc = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb", "/warnaserror+", "/ruleset:" & ruleSetFile.Path, "/nowarn:42376" }) exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) ' Diagnostics thrown as error: command line always overrides ruleset. output = outWriter.ToString() Assert.Contains("error Warning01", output, StringComparison.Ordinal) Assert.Contains("error Warning03", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub Analyzer_CommandLineOverridesRuleset2() Dim source = "Imports System " + vbCrLf + "Public Class Tester" + vbCrLf + "End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim rulesetSource = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed"> <Rule Id="Warning01" Action="Error"/> <Rule Id="Warning03" Action="Warning"/> </Rules> </RuleSet> Dim ruleSetFile = CreateRuleSetFile(rulesetSource) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb", "/ruleset:" & ruleSetFile.Path, "/nowarn" }) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) ' Diagnostics suppressed: command line always overrides ruleset. Dim output = outWriter.ToString() Assert.DoesNotContain("Warning01", output, StringComparison.Ordinal) Assert.DoesNotContain("BC31072", output, StringComparison.Ordinal) Assert.DoesNotContain("Warning03", output, StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) vbc = New MockVisualBasicCompiler(Nothing, dir.Path, { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb", "/nowarn", "/ruleset:" & ruleSetFile.Path }) exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) ' Diagnostics suppressed: command line always overrides ruleset. output = outWriter.ToString() Assert.DoesNotContain("Warning01", output, StringComparison.Ordinal) Assert.DoesNotContain("BC31072", output, StringComparison.Ordinal) Assert.DoesNotContain("Warning03", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub Analyzers_WithRuleSetIncludeAll() Dim source = "Imports System \r\n Public Class Tester \r\n Public Sub Goo() \r\n Dim x As Integer \r\n End Sub \r\n End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim rulesetSource = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <IncludeAll Action="Error"/> <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed"> <Rule Id="Warning01" Action="Error"/> <Rule Id="Test02" Action="Warning"/> <Rule Id="Warning03" Action="None"/> </Rules> </RuleSet> Dim ruleSetFile = CreateRuleSetFile(rulesetSource) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.vb", "/ruleset:" + ruleSetFile.Path}) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) ' Compiler warnings as errors Assert.True(outWriter.ToString().Contains("error BC42376")) ' User diagnostics not thrown due to compiler errors Assert.False(outWriter.ToString().Contains("Warning01")) Assert.False(outWriter.ToString().Contains("Warning03")) CleanupAllGeneratedFiles(file.Path) End Sub Private Function CreateRuleSetFile(source As XDocument) As TempFile Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.ruleset") file.WriteAllText(source.ToString()) Return file End Function <Fact> Public Sub RulesetSwitchPositive() Dim source = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <IncludeAll Action="Warning"/> <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed"> <Rule Id="CA1012" Action="Error"/> <Rule Id="CA1013" Action="Warning"/> <Rule Id="CA1014" Action="None"/> </Rules> </RuleSet> Dim file = CreateRuleSetFile(source) Dim parsedArgs = DefaultParse(New String() {"/ruleset:" + file.Path, "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(expected:=file.Path, actual:=parsedArgs.RuleSetPath) Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1012")) Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions("CA1012") = ReportDiagnostic.Error) Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1013")) Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions("CA1013") = ReportDiagnostic.Warn) Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1014")) Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions("CA1014") = ReportDiagnostic.Suppress) Assert.True(parsedArgs.CompilationOptions.GeneralDiagnosticOption = ReportDiagnostic.Warn) End Sub <Fact> Public Sub RuleSetSwitchQuoted() Dim source = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <IncludeAll Action="Warning"/> <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed"> <Rule Id="CA1012" Action="Error"/> <Rule Id="CA1013" Action="Warning"/> <Rule Id="CA1014" Action="None"/> </Rules> </RuleSet> Dim file = CreateRuleSetFile(source) Dim parsedArgs = DefaultParse(New String() {"/ruleset:" + """" + file.Path + """", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(expected:=file.Path, actual:=parsedArgs.RuleSetPath) End Sub <Fact> Public Sub RulesetSwitchParseErrors() Dim parsedArgs = DefaultParse(New String() {"/ruleset", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("ruleset", ":<file>")) Assert.Null(parsedArgs.RuleSetPath) parsedArgs = DefaultParse(New String() {"/ruleset", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("ruleset", ":<file>")) Assert.Null(parsedArgs.RuleSetPath) parsedArgs = DefaultParse(New String() {"/ruleset:blah", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah"), "File not found.")) Assert.Equal(expected:=Path.Combine(TempRoot.Root, "blah"), actual:=parsedArgs.RuleSetPath) parsedArgs = DefaultParse(New String() {"/ruleset:blah;blah.ruleset", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah;blah.ruleset"), "File not found.")) Assert.Equal(expected:=Path.Combine(TempRoot.Root, "blah;blah.ruleset"), actual:=parsedArgs.RuleSetPath) Dim file = CreateRuleSetFile(New XDocument()) parsedArgs = DefaultParse(New String() {"/ruleset:" + file.Path, "a.cs"}, _baseDirectory) 'parsedArgs.Errors.Verify( ' Diagnostic(ERRID.ERR_CantReadRulesetFile).WithArguments(file.Path, "Root element is missing.")) Assert.Equal(expected:=file.Path, actual:=parsedArgs.RuleSetPath) Dim err = parsedArgs.Errors.Single() Assert.Equal(ERRID.ERR_CantReadRulesetFile, err.Code) Assert.Equal(2, err.Arguments.Count) Assert.Equal(file.Path, DirectCast(err.Arguments(0), String)) Dim currentUICultureName = Thread.CurrentThread.CurrentUICulture.Name If currentUICultureName.Length = 0 OrElse currentUICultureName.StartsWith("en", StringComparison.OrdinalIgnoreCase) Then Assert.Equal(err.Arguments(1), "Root element is missing.") End If End Sub <Fact> Public Sub Target_SimpleTests() Dim parsedArgs = DefaultParse({"/target:exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/t:module", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:library", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/TARGET:winexe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:winmdobj", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:appcontainerexe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:winexe", "/T:exe", "/target:module", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/t", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("t", ":exe|winexe|library|module|appcontainerexe|winmdobj")) parsedArgs = DefaultParse({"/target:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("target", ":exe|winexe|library|module|appcontainerexe|winmdobj")) parsedArgs = DefaultParse({"/target:xyz", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("target", "xyz")) parsedArgs = DefaultParse({"/T+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/T+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/TARGET-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/TARGET-:")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact> Public Sub Target_SimpleTestsNoSourceFile() Dim parsedArgs = DefaultParse({"/target:exe"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/t:module"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:library"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/TARGET:winexe"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:winmdobj"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:appcontainerexe"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/target:winexe", "/T:exe", "/target:module"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind) parsedArgs = DefaultParse({"/t"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("t", ":exe|winexe|library|module|appcontainerexe|winmdobj"), Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) parsedArgs = DefaultParse({"/target:"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("target", ":exe|winexe|library|module|appcontainerexe|winmdobj"), Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) parsedArgs = DefaultParse({"/target:xyz"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("target", "xyz"), Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) parsedArgs = DefaultParse({"/T+"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/T+"), Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/TARGET-:"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/TARGET-:"), Diagnostic(ERRID.ERR_NoSources).WithLocation(1, 1)) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact> Public Sub Utf8Output() Dim parsedArgs = DefaultParse({"/utf8output", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.Utf8Output) parsedArgs = DefaultParse({"/utf8output+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(True, parsedArgs.Utf8Output) parsedArgs = DefaultParse({"/utf8output-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.Utf8Output) ' default parsedArgs = DefaultParse({"/nologo", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.Utf8Output) ' overriding parsedArgs = DefaultParse({"/utf8output+", "/utf8output-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(False, parsedArgs.Utf8Output) ' errors parsedArgs = DefaultParse({"/utf8output:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("utf8output")) End Sub <Fact> Public Sub Debug() Dim platformPdbKind = If(PathUtilities.IsUnixLikePlatform, DebugInformationFormat.PortablePdb, DebugInformationFormat.Pdb) Dim parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) Assert.False(parsedArgs.EmitPdb) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.False(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug+", "/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.False(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug:full", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug:FULL", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug:pdbonly", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug:portable", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, DebugInformationFormat.PortablePdb) parsedArgs = DefaultParse({"/debug:embedded", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, DebugInformationFormat.Embedded) parsedArgs = DefaultParse({"/debug:PDBONLY", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug:full", "/debug:pdbonly", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind) parsedArgs = DefaultParse({"/debug:pdbonly", "/debug:full", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat) parsedArgs = DefaultParse({"/debug:pdbonly", "/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.False(parsedArgs.EmitPdb) Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat) parsedArgs = DefaultParse({"/debug:pdbonly", "/debug-", "/debug", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat) parsedArgs = DefaultParse({"/debug:pdbonly", "/debug-", "/debug+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat) parsedArgs = DefaultParse({"/debug:embedded", "/debug-", "/debug+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.EmitPdb) Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat) parsedArgs = DefaultParse({"/debug:embedded", "/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.False(parsedArgs.EmitPdb) Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat) parsedArgs = DefaultParse({"/debug:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("debug", "")) parsedArgs = DefaultParse({"/debug:+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("debug", "+")) parsedArgs = DefaultParse({"/debug:invalid", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("debug", "invalid")) parsedArgs = DefaultParse({"/debug-:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("debug")) parsedArgs = DefaultParse({"/pdb:something", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/pdb:something")) End Sub <Fact> Public Sub SourceLink() Dim parsedArgs = DefaultParse({"/sourcelink:sl.json", "/debug:portable", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(_baseDirectory, "sl.json"), parsedArgs.SourceLink) parsedArgs = DefaultParse({"/sourcelink:sl.json", "/debug:embedded", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(_baseDirectory, "sl.json"), parsedArgs.SourceLink) parsedArgs = DefaultParse({"/sourcelink:""s l.json""", "/debug:embedded", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(_baseDirectory, "s l.json"), parsedArgs.SourceLink) parsedArgs = DefaultParse({"/sourcelink:sl.json", "/debug:full", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/sourcelink:sl.json", "/debug:pdbonly", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/sourcelink:sl.json", "/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SourceLinkRequiresPdb)) parsedArgs = DefaultParse({"/sourcelink:sl.json", "/debug+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/sourcelink:sl.json", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SourceLinkRequiresPdb)) End Sub <Fact> Public Sub SourceLink_EndToEnd_EmbeddedPortable() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText(" Class C Public Shared Sub Main() End Sub End Class") Dim sl = dir.CreateFile("sl.json") sl.WriteAllText("{ ""documents"" : {} }") Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/debug:embedded", "/sourcelink:sl.json", "a.vb"}) Dim exitCode As Integer = vbc.Run(outWriter) Assert.Equal(0, exitCode) Dim peStream = File.OpenRead(Path.Combine(dir.Path, "a.exe")) Using peReader = New PEReader(peStream) Dim entry = peReader.ReadDebugDirectory().Single(Function(e) e.Type = DebugDirectoryEntryType.EmbeddedPortablePdb) Using mdProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry) Dim blob = mdProvider.GetMetadataReader().GetSourceLinkBlob() AssertEx.Equal(File.ReadAllBytes(sl.Path), blob) End Using End Using CleanupAllGeneratedFiles(src.Path) End Sub <Fact> Public Sub SourceLink_EndToEnd_Portable() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText(" Class C Public Shared Sub Main() End Sub End Class") Dim sl = dir.CreateFile("sl.json") sl.WriteAllText("{ ""documents"" : {} }") Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/debug:portable", "/sourcelink:sl.json", "a.vb"}) Dim exitCode As Integer = vbc.Run(outWriter) Assert.Equal(0, exitCode) Dim pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")) Using mdProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream) Dim blob = mdProvider.GetMetadataReader().GetSourceLinkBlob() AssertEx.Equal(File.ReadAllBytes(sl.Path), blob) End Using CleanupAllGeneratedFiles(src.Path) End Sub <Fact> Public Sub Embed() Dim parsedArgs = DefaultParse({"a.vb "}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Empty(parsedArgs.EmbeddedFiles) parsedArgs = DefaultParse({"/embed", "/debug:portable", "a.vb", "b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal(parsedArgs.SourceFiles, parsedArgs.EmbeddedFiles) AssertEx.Equal( {"a.vb", "b.vb", "c.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:a.vb", "/embed:b.vb", "/debug:embedded", "a.vb", "b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a.vb", "b.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:a.vb;b.vb", "/debug:portable", "a.vb", "b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a.vb", "b.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:a.vb,b.vb", "/debug:portable", "a.vb", "b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a.vb", "b.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:""a,b.vb""", "/debug:portable", "a,b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a,b.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:\""a,b.vb\""", "/debug:portable", "a,b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a,b.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:\""""a.vb,b.vb""\""", "/debug:portable", "a.vb", "b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a.vb", "b.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed:a.txt", "/embed", "/debug:portable", "a.vb", "b.vb", "c.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertEx.Equal( {"a.txt", "a.vb", "b.vb", "c.vb"}.Select(Function(f) Path.Combine(_baseDirectory, f)), parsedArgs.EmbeddedFiles.Select(Function(f) f.Path)) parsedArgs = DefaultParse({"/embed", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_CannotEmbedWithoutPdb)) parsedArgs = DefaultParse({"/embed:a.txt", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_CannotEmbedWithoutPdb)) parsedArgs = DefaultParse({"/embed", "/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_CannotEmbedWithoutPdb)) parsedArgs = DefaultParse({"/embed:a.txt", "/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_CannotEmbedWithoutPdb)) parsedArgs = DefaultParse({"/embed", "/debug:full", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/embed", "/debug:pdbonly", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/embed", "/debug+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() End Sub <Theory> <InlineData("/debug:portable", "/embed", {"embed.vb", "embed2.vb", "embed.xyz"})> <InlineData("/debug:portable", "/embed:embed.vb", {"embed.vb", "embed.xyz"})> <InlineData("/debug:portable", "/embed:embed2.vb", {"embed2.vb"})> <InlineData("/debug:portable", "/embed:embed.xyz", {"embed.xyz"})> <InlineData("/debug:embedded", "/embed", {"embed.vb", "embed2.vb", "embed.xyz"})> <InlineData("/debug:embedded", "/embed:embed.vb", {"embed.vb", "embed.xyz"})> <InlineData("/debug:embedded", "/embed:embed2.vb", {"embed2.vb"})> <InlineData("/debug:embedded", "/embed:embed.xyz", {"embed.xyz"})> <InlineData("/debug:full", "/embed", {"embed.vb", "embed2.vb", "embed.xyz"})> <InlineData("/debug:full", "/embed:embed.vb", {"embed.vb", "embed.xyz"})> <InlineData("/debug:full", "/embed:embed2.vb", {"embed2.vb"})> <InlineData("/debug:full", "/embed:embed.xyz", {"embed.xyz"})> Public Sub Embed_EndToEnd(debugSwitch As String, embedSwitch As String, expectedEmbedded As String()) ' embed.vb: large enough To compress, has #line directives Const embed_vb = "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Class Program Shared Sub Main() #ExternalSource(""embed.xyz"", 1) System.Console.WriteLine(""Hello, World"") System.Console.WriteLine(""Goodbye, World"") #End ExternalSource End Sub End Class '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''" ' embed2.vb: small enough to not compress, no sequence points Const embed2_vb = "Class C End Class" ' target of #ExternalSource Const embed_xyz = "print Hello, World print Goodbye, World" Assert.True(embed_vb.Length >= EmbeddedText.CompressionThreshold) Assert.True(embed2_vb.Length < EmbeddedText.CompressionThreshold) Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("embed.vb") Dim src2 = dir.CreateFile("embed2.vb") Dim txt = dir.CreateFile("embed.xyz") src.WriteAllText(embed_vb) src2.WriteAllText(embed2_vb) txt.WriteAllText(embed_xyz) Dim expectedEmbeddedMap = New Dictionary(Of String, String)() If expectedEmbedded.Contains("embed.vb") Then expectedEmbeddedMap.Add(src.Path, embed_vb) End If If expectedEmbedded.Contains("embed2.vb") Then expectedEmbeddedMap.Add(src2.Path, embed2_vb) End If If expectedEmbedded.Contains("embed.xyz") Then expectedEmbeddedMap.Add(txt.Path, embed_xyz) End If Dim output = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", debugSwitch, embedSwitch, "embed.vb", "embed2.vb"}) Dim exitCode = vbc.Run(output) Assert.Equal("", output.ToString().Trim()) Assert.Equal(0, exitCode) Select Case debugSwitch Case "/debug:embedded" ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb:=True) Case "/debug:portable" ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb:=False) Case "/debug:full" ValidateEmbeddedSources_Windows(expectedEmbeddedMap, dir) End Select Assert.Empty(expectedEmbeddedMap) CleanupAllGeneratedFiles(src.Path) End Sub Private Shared Sub ValidateEmbeddedSources_Portable(expectedEmbeddedMap As Dictionary(Of String, String), dir As TempDirectory, isEmbeddedPdb As Boolean) Using peReader As New PEReader(File.OpenRead(Path.Combine(dir.Path, "embed.exe"))) Dim entry = peReader.ReadDebugDirectory().SingleOrDefault(Function(e) e.Type = DebugDirectoryEntryType.EmbeddedPortablePdb) Assert.Equal(isEmbeddedPdb, entry.DataSize > 0) Using mdProvider As MetadataReaderProvider = If( isEmbeddedPdb, peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry), MetadataReaderProvider.FromPortablePdbStream(File.OpenRead(Path.Combine(dir.Path, "embed.pdb")))) Dim mdReader = mdProvider.GetMetadataReader() For Each handle In mdReader.Documents Dim doc = mdReader.GetDocument(handle) Dim docPath = mdReader.GetString(doc.Name) Dim embeddedSource = mdReader.GetEmbeddedSource(handle) If embeddedSource Is Nothing Then Continue For End If Assert.True(TypeOf embeddedSource.Encoding Is UTF8Encoding AndAlso embeddedSource.Encoding.GetPreamble().Length = 0) Assert.Equal(expectedEmbeddedMap(docPath), embeddedSource.ToString()) Assert.True(expectedEmbeddedMap.Remove(docPath)) Next End Using End Using End Sub Private Shared Sub ValidateEmbeddedSources_Windows(expectedEmbeddedMap As Dictionary(Of String, String), dir As TempDirectory) Dim symReader As ISymUnmanagedReader5 = Nothing Try symReader = SymReaderFactory.CreateReader(File.OpenRead(Path.Combine(dir.Path, "embed.pdb"))) For Each doc In symReader.GetDocuments() Dim docPath = doc.GetName() Dim sourceBlob = doc.GetEmbeddedSource() If sourceBlob.Array Is Nothing Then Continue For End If Dim sourceStr = Encoding.UTF8.GetString(sourceBlob.Array, sourceBlob.Offset, sourceBlob.Count) Assert.Equal(expectedEmbeddedMap(docPath), sourceStr) Assert.True(expectedEmbeddedMap.Remove(docPath)) Next Finally symReader?.Dispose() End Try End Sub <CompilerTrait(CompilerFeature.Determinism)> <Fact> Public Sub PathMapParser() Dim s = PathUtilities.DirectorySeparatorStr Dim parsedArgs = DefaultParse({"/pathmap:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/pathmap:").WithLocation(1, 1) ) Assert.Equal(ImmutableArray.Create(Of KeyValuePair(Of String, String))(), parsedArgs.PathMap) parsedArgs = DefaultParse({"/pathmap:K1=V1", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("K1" & s, "V1" & s), parsedArgs.PathMap(0)) parsedArgs = DefaultParse({$"/pathmap:abc{s}=/", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("abc" & s, "/"), parsedArgs.PathMap(0)) parsedArgs = DefaultParse({"/pathmap:K1=V1,K2=V2", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("K1" & s, "V1" & s), parsedArgs.PathMap(0)) Assert.Equal(KeyValuePairUtil.Create("K2" & s, "V2" & s), parsedArgs.PathMap(1)) parsedArgs = DefaultParse({"/pathmap:,", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(ImmutableArray.Create(Of KeyValuePair(Of String, String))(), parsedArgs.PathMap) parsedArgs = DefaultParse({"/pathmap:,,", "a.vb"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Count()) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(0).Code) parsedArgs = DefaultParse({"/pathmap:,,,", "a.vb"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Count()) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(0).Code) parsedArgs = DefaultParse({"/pathmap:k=,=v", "a.vb"}, _baseDirectory) Assert.Equal(2, parsedArgs.Errors.Count()) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(0).Code) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(1).Code) parsedArgs = DefaultParse({"/pathmap:k=v=bad", "a.vb"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Count()) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(0).Code) parsedArgs = DefaultParse({"/pathmap:k=", "a.vb"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Count()) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(0).Code) parsedArgs = DefaultParse({"/pathmap:=v", "a.vb"}, _baseDirectory) Assert.Equal(1, parsedArgs.Errors.Count()) Assert.Equal(ERRID.ERR_InvalidPathMap, parsedArgs.Errors(0).Code) parsedArgs = DefaultParse({"/pathmap:""supporting spaces=is hard""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("supporting spaces" & s, "is hard" & s), parsedArgs.PathMap(0)) parsedArgs = DefaultParse({"/pathmap:""K 1=V 1"",""K 2=V 2""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("K 1" & s, "V 1" & s), parsedArgs.PathMap(0)) Assert.Equal(KeyValuePairUtil.Create("K 2" & s, "V 2" & s), parsedArgs.PathMap(1)) parsedArgs = DefaultParse({"/pathmap:""K 1""=""V 1"",""K 2""=""V 2""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("K 1" & s, "V 1" & s), parsedArgs.PathMap(0)) Assert.Equal(KeyValuePairUtil.Create("K 2" & s, "V 2" & s), parsedArgs.PathMap(1)) parsedArgs = DefaultParse({"/pathmap:""a ==,,b""=""1,,== 2"",""x ==,,y""=""3 4"",", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("a =,b" & s, "1,= 2" & s), parsedArgs.PathMap(0)) Assert.Equal(KeyValuePairUtil.Create("x =,y" & s, "3 4" & s), parsedArgs.PathMap(1)) parsedArgs = DefaultParse({"/pathmap:C:\temp\=/_1/,C:\temp\a\=/_2/,C:\temp\a\b\=/_3/", "a.cs", "a\b.cs", "a\b\c.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(KeyValuePairUtil.Create("C:\temp\a\b\", "/_3/"), parsedArgs.PathMap(0)) Assert.Equal(KeyValuePairUtil.Create("C:\temp\a\", "/_2/"), parsedArgs.PathMap(1)) Assert.Equal(KeyValuePairUtil.Create("C:\temp\", "/_1/"), parsedArgs.PathMap(2)) End Sub ' PathMapKeepsCrossPlatformRoot and PathMapInconsistentSlashes should be in an ' assembly that is ran cross-platform, but as no visual basic test assemblies are ' run cross-platform, put this here in the hopes that this will eventually be ported. <Theory> <InlineData("C:\", "/", "C:\", "/")> <InlineData("C:\temp\", "/temp/", "C:\temp", "/temp")> <InlineData("C:\temp\", "/temp/", "C:\temp\", "/temp/")> <InlineData("/", "C:\", "/", "C:\")> <InlineData("/temp/", "C:\temp\", "/temp", "C:\temp")> <InlineData("/temp/", "C:\temp\", "/temp/", "C:\temp\")> Public Sub PathMapKeepsCrossPlatformRoot(expectedFrom As String, expectedTo As String, sourceFrom As String, sourceTo As String) Dim pathmapArg = $"/pathmap:{sourceFrom}={sourceTo}" Dim parsedArgs = VisualBasicCommandLineParser.Default.Parse({pathmapArg, "a.vb"}, TempRoot.Root, RuntimeEnvironment.GetRuntimeDirectory(), Nothing) parsedArgs.Errors.Verify() Dim expected = New KeyValuePair(Of String, String)(expectedFrom, expectedTo) Assert.Equal(expected, parsedArgs.PathMap(0)) End Sub <Fact> Public Sub PathMapInconsistentSlashes() Dim Parse = Function(args() As String) As VisualBasicCommandLineArguments Dim parsedArgs = VisualBasicCommandLineParser.Default.Parse(args, TempRoot.Root, RuntimeEnvironment.GetRuntimeDirectory(), Nothing) parsedArgs.Errors.Verify() Return parsedArgs End Function Dim sep = PathUtilities.DirectorySeparatorChar Assert.Equal(New KeyValuePair(Of String, String)("C:\temp/goo" + sep, "/temp\goo" + sep), Parse({"/pathmap:C:\temp/goo=/temp\goo", "a.vb"}).PathMap(0)) Assert.Equal(New KeyValuePair(Of String, String)("noslash" + sep, "withoutslash" + sep), Parse({"/pathmap:noslash=withoutslash", "a.vb"}).PathMap(0)) Dim doublemap = Parse({"/pathmap:/temp=/goo,/temp/=/bar", "a.vb"}).PathMap Assert.Equal(New KeyValuePair(Of String, String)("/temp/", "/goo/"), doublemap(0)) Assert.Equal(New KeyValuePair(Of String, String)("/temp/", "/bar/"), doublemap(1)) End Sub <Fact> Public Sub NothingBaseDirectoryNotAddedToKeyFileSearchPaths() Dim args As VisualBasicCommandLineArguments = VisualBasicCommandLineParser.Default.Parse(New String() {}, Nothing, RuntimeEnvironment.GetRuntimeDirectory()) AssertEx.Equal(ImmutableArray.Create(Of String)(), args.KeyFileSearchPaths) End Sub <Fact> <WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")> Public Sub SdkPathArg() Dim parentDir = Temp.CreateDirectory() Dim sdkDir = parentDir.CreateDirectory("sdk") Dim sdkPath = sdkDir.Path Dim parser = VisualBasicCommandLineParser.Default.Parse({$"-sdkPath:{sdkPath}"}, parentDir.Path, Nothing) AssertEx.Equal(ImmutableArray.Create(sdkPath), parser.ReferencePaths) End Sub <Fact> <WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")> Public Sub SdkPathNoArg() Dim parentDir = Temp.CreateDirectory() Dim parser = VisualBasicCommandLineParser.Default.Parse({"file.vb", "-sdkPath", $"-out:{parentDir.Path}"}, parentDir.Path, Nothing) parser.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired, arguments:={"sdkpath", ":<path>"}).WithLocation(1, 1), Diagnostic(ERRID.WRN_CannotFindStandardLibrary1).WithArguments("System.dll").WithLocation(1, 1), Diagnostic(ERRID.ERR_LibNotFound).WithArguments("Microsoft.VisualBasic.dll").WithLocation(1, 1)) End Sub <Fact> <WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")> Public Sub SdkPathFollowedByNoSdkPath() Dim parentDir = Temp.CreateDirectory() Dim parser = VisualBasicCommandLineParser.Default.Parse({"file.vb", $"-out:{parentDir.Path}", "-sdkPath:path/to/sdk", "/noSdkPath"}, parentDir.Path, Nothing) AssertEx.Equal(ImmutableArray(Of String).Empty, parser.ReferencePaths) End Sub <Fact> <WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")> Public Sub NoSdkPathFollowedBySdkPath() Dim parentDir = Temp.CreateDirectory() Dim sdkDir = parentDir.CreateDirectory("sdk") Dim parser = VisualBasicCommandLineParser.Default.Parse({"file.vb", $"-out:{parentDir.Path}", "/noSdkPath", $"-sdkPath:{sdkDir.Path}"}, parentDir.Path, Nothing) AssertEx.Equal(ImmutableArray.Create(sdkDir.Path), parser.ReferencePaths) End Sub <Fact> <WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")> Public Sub NoSdkPathReferenceSystemDll() Dim source = " Module M End Module " Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/preferreduilang:en", "/nosdkpath", "/t:library", "a.vb"}) Dim exitCode = vbc.Run(outWriter, Nothing) Dim output = outWriter.ToString().Trim() Assert.Equal(1, exitCode) Assert.Contains("vbc : error BC2017: could not find library 'Microsoft.VisualBasic.dll'", output) CleanupAllGeneratedFiles(file.Path) End Sub <CompilerTrait(CompilerFeature.Determinism)> <Fact> Public Sub PathMapPdbDeterminism() Dim assertPdbEmit = Sub(dir As TempDirectory, pePdbPath As String, extraArgs As String()) Dim source = <compilation> Imports System Module Program Sub Main() End Sub End Module </compilation> Dim src = dir.CreateFile("a.vb").WriteAllText(source.Value) Dim pdbPath = Path.Combine(dir.Path, "a.pdb") Dim defaultArgs = {"/nologo", "/debug", "a.vb"} Dim isDeterministic = extraArgs.Contains("/deterministic") Dim args = defaultArgs.Concat(extraArgs).ToArray() Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(dir.Path, args) Dim exitCode = vbc.Run(outWriter) Assert.Equal(0, exitCode) Dim exePath = Path.Combine(dir.Path, "a.exe") Assert.True(File.Exists(exePath)) Assert.True(File.Exists(pdbPath)) Using peStream = File.OpenRead(exePath) PdbValidation.ValidateDebugDirectory(peStream, Nothing, pePdbPath, hashAlgorithm:=Nothing, hasEmbeddedPdb:=False, isDeterministic) End Using End Sub ' No mappings Using dir As New DisposableDirectory(Temp) Dim pePdbPath = Path.Combine(dir.Path, "a.pdb") assertPdbEmit(dir, pePdbPath, {}) End Using ' Simple mapping Using dir As New DisposableDirectory(Temp) Dim pePdbPath = "q:\a.pdb" assertPdbEmit(dir, pePdbPath, {$"/pathmap:{dir.Path}=q:\"}) End Using ' Simple mapping deterministic Using dir As New DisposableDirectory(Temp) Dim pePdbPath = "q:\a.pdb" assertPdbEmit(dir, pePdbPath, {$"/pathmap:{dir.Path}=q:\", "/deterministic"}) End Using ' Partial mapping Using dir As New DisposableDirectory(Temp) Dim subDir = dir.CreateDirectory("example") Dim pePdbPath = "q:\example\a.pdb" assertPdbEmit(subDir, pePdbPath, {$"/pathmap:{dir.Path}=q:\"}) End Using ' Legacy feature flag Using dir As New DisposableDirectory(Temp) Dim pePdbPath = Path.Combine(dir.Path, "a.pdb") assertPdbEmit(dir, "a.pdb", {"/features:pdb-path-determinism"}) End Using ' Unix path map Using dir As New DisposableDirectory(Temp) Dim pdbPath = Path.Combine(dir.Path, "a.pdb") assertPdbEmit(dir, "/a.pdb", {$"/pathmap:{dir.Path}=/"}) End Using ' Multi-specified path map with mixed slashes Using dir As New DisposableDirectory(Temp) Dim pdbPath = Path.Combine(dir.Path, "a.pdb") assertPdbEmit(dir, "/goo/a.pdb", {$"/pathmap:{dir.Path}=/goo,{dir.Path}{PathUtilities.DirectorySeparatorChar}=/bar"}) End Using End Sub <WorkItem(540891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540891")> <Fact> Public Sub ParseOut() Const baseDirectory As String = "C:\abc\def\baz" ' Should preserve fully qualified paths Dim parsedArgs = DefaultParse({"/out:C:\MyFolder\MyBinary.dll", "/t:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("MyBinary", parsedArgs.CompilationName) Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName) Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName) Assert.Equal("C:\MyFolder", parsedArgs.OutputDirectory) parsedArgs = DefaultParse({"/out:""C:\My Folder\MyBinary.dll""", "/t:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("MyBinary", parsedArgs.CompilationName) Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName) Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName) Assert.Equal("C:\My Folder", parsedArgs.OutputDirectory) parsedArgs = DefaultParse({"/refout:", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("refout", ":<file>").WithLocation(1, 1)) parsedArgs = DefaultParse({"/refout:ref.dll", "/refonly", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1)) parsedArgs = DefaultParse({"/refonly:incorrect", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("refonly").WithLocation(1, 1)) parsedArgs = DefaultParse({"/refout:ref.dll", "/target:module", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1)) parsedArgs = DefaultParse({"/refout:ref.dll", "/link:b", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/refonly", "/link:b", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/refonly", "/target:module", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1)) parsedArgs = DefaultParse({"/out:C:\""My Folder""\MyBinary.dll", "/t:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("C:""My Folder\MyBinary.dll").WithLocation(1, 1)) parsedArgs = DefaultParse({"/out:MyBinary.dll", "/t:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("MyBinary", parsedArgs.CompilationName) Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName) Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) parsedArgs = DefaultParse({"/out:Ignored.dll", "/out:MyBinary.dll", "/t:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("MyBinary", parsedArgs.CompilationName) Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName) Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) parsedArgs = DefaultParse({"/out:..\MyBinary.dll", "/t:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("MyBinary", parsedArgs.CompilationName) Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName) Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName) Assert.Equal("C:\abc\def", parsedArgs.OutputDirectory) ' not specified: exe parsedArgs = DefaultParse({"a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.exe", parsedArgs.OutputFileName) Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) ' not specified: dll parsedArgs = DefaultParse({"/target:library", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.dll", parsedArgs.OutputFileName) Assert.Equal("a.dll", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) ' not specified: module parsedArgs = DefaultParse({"/target:module", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Null(parsedArgs.CompilationName) Assert.Equal("a.netmodule", parsedArgs.OutputFileName) Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) ' not specified: appcontainerexe parsedArgs = DefaultParse({"/target:appcontainerexe", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.exe", parsedArgs.OutputFileName) Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) ' not specified: winmdobj parsedArgs = DefaultParse({"/target:winmdobj", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.winmdobj", parsedArgs.OutputFileName) Assert.Equal("a.winmdobj", parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) ' drive-relative path: Dim currentDrive As Char = Directory.GetCurrentDirectory()(0) parsedArgs = DefaultParse({currentDrive + ":a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.vb")) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) Assert.Equal(baseDirectory, parsedArgs.OutputDirectory) ' UNC parsedArgs = DefaultParse({"/out:\\b", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("\\b")) Assert.Equal("a.exe", parsedArgs.OutputFileName) Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/out:\\server\share\file.exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("\\server\share", parsedArgs.OutputDirectory) Assert.Equal("file.exe", parsedArgs.OutputFileName) Assert.Equal("file", parsedArgs.CompilationName) Assert.Equal("file.exe", parsedArgs.CompilationOptions.ModuleName) ' invalid name parsedArgs = DefaultParse({"/out:a.b" & vbNullChar & "b", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("a.b" & vbNullChar & "b")) Assert.Equal("a.exe", parsedArgs.OutputFileName) Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) ' Temp Skip: Unicode? ' parsedArgs = DefaultParse({"/out:a" & ChrW(&HD800) & "b.dll", "a.vb"}, _baseDirectory) ' parsedArgs.Errors.Verify( ' Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("a" & ChrW(&HD800) & "b.dll")) ' Assert.Equal("a.exe", parsedArgs.OutputFileName) ' Assert.Equal("a", parsedArgs.CompilationName) ' Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) ' Temp Skip: error message changed (path) 'parsedArgs = DefaultParse({"/out:"" a.dll""", "a.vb"}, _baseDirectory) 'parsedArgs.Errors.Verify( ' Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(" a.dll")) 'Assert.Equal("a.exe", parsedArgs.OutputFileName) 'Assert.Equal("a", parsedArgs.CompilationName) 'Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) ' Dev11 reports BC2012: can't open 'a<>.z' for writing parsedArgs = DefaultParse({"/out:""a<>.dll""", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("a<>.dll")) Assert.Equal("a.exe", parsedArgs.OutputFileName) Assert.Equal("a", parsedArgs.CompilationName) Assert.Equal("a.exe", parsedArgs.CompilationOptions.ModuleName) ' bad value parsedArgs = DefaultParse({"/out", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("out", ":<file>")) parsedArgs = DefaultParse({"/OUT:", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("out", ":<file>")) parsedArgs = DefaultParse({"/REFOUT:", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("refout", ":<file>")) parsedArgs = DefaultParse({"/refout:ref.dll", "/refonly", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1)) parsedArgs = DefaultParse({"/out+", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/out+")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/out-:", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/out-:")) ' TODO: Dev11 reports ERR_ArgumentRequired parsedArgs = DefaultParse({"/out:.exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".exe")) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/t:exe", "/out:.exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".exe")) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/t:library", "/out:.dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".dll")) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/t:module", "/out:.netmodule", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(".netmodule", parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({".vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".exe")) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/t:exe", ".vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".exe")) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/t:library", ".vb"}, _baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".dll")) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/t:module", ".vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(".netmodule", parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationName) Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName) End Sub <Fact> Public Sub ParseOut2() ' exe Dim parsedArgs = DefaultParse({"/out:.x", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(".x", parsedArgs.CompilationName) Assert.Equal(".x.exe", parsedArgs.OutputFileName) Assert.Equal(".x.exe", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:winexe", "/out:.x.eXe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(".x", parsedArgs.CompilationName) Assert.Equal(".x.eXe", parsedArgs.OutputFileName) Assert.Equal(".x.eXe", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:winexe", "/out:.exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".exe")) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) ' dll parsedArgs = DefaultParse({"/target:library", "/out:.x", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(".x", parsedArgs.CompilationName) Assert.Equal(".x.dll", parsedArgs.OutputFileName) Assert.Equal(".x.dll", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:library", "/out:.X.Dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(".X", parsedArgs.CompilationName) Assert.Equal(".X.Dll", parsedArgs.OutputFileName) Assert.Equal(".X.Dll", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:library", "/out:.dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(".dll")) Assert.Null(parsedArgs.CompilationName) Assert.Null(parsedArgs.OutputFileName) Assert.Null(parsedArgs.CompilationOptions.ModuleName) ' module parsedArgs = DefaultParse({"/target:module", "/out:.x", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Null(parsedArgs.CompilationName) Assert.Equal(".x", parsedArgs.OutputFileName) Assert.Equal(".x", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:module", "/out:x.dll", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Null(parsedArgs.CompilationName) Assert.Equal("x.dll", parsedArgs.OutputFileName) Assert.Equal("x.dll", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:module", "/out:.x.netmodule", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Null(parsedArgs.CompilationName) Assert.Equal(".x.netmodule", parsedArgs.OutputFileName) Assert.Equal(".x.netmodule", parsedArgs.CompilationOptions.ModuleName) parsedArgs = DefaultParse({"/target:module", "/out:x", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Null(parsedArgs.CompilationName) Assert.Equal("x.netmodule", parsedArgs.OutputFileName) Assert.Equal("x.netmodule", parsedArgs.CompilationOptions.ModuleName) End Sub <Fact, WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> Public Sub ConsistentErrorMessageWhenProvidingNoKeyFile() Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/keyfile:", "/target:library", "/nologo", "/preferreduilang:en", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'keyfile' requires ':<file>'", outWriter.ToString().Trim()) End Sub <Fact, WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> Public Sub ConsistentErrorMessageWhenProvidingEmptyKeyFile() Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/keyfile:""""", "/target:library", "/nologo", "/preferreduilang:en", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'keyfile' requires ':<file>'", outWriter.ToString().Trim()) End Sub <Fact, WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> Public Sub ConsistentErrorMessageWhenProvidingNoKeyFile_PublicSign() Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/keyfile:", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'keyfile' requires ':<file>'", outWriter.ToString().Trim()) End Sub <Fact, WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> Public Sub ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign() Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/keyfile:""""", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'keyfile' requires ':<file>'", outWriter.ToString().Trim()) End Sub <Fact, WorkItem(531020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531020")> Public Sub ParseDocBreak1() Const baseDirectory As String = "C:\abc\def\baz" ' In dev11, this appears to be equivalent to /doc- (i.e. don't parse and don't output). Dim parsedArgs = DefaultParse({"/doc:""""", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("doc", ":<file>")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) End Sub <Fact, WorkItem(705173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705173")> Public Sub Ensure_UTF8_Explicit_Prefix_In_Documentation_Comment_File() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /doc:{1}\src.xml /t:library {0}", src.ToString(), dir.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Dim fileContents = File.ReadAllBytes(dir.ToString() & "\src.xml") Assert.InRange(fileContents.Length, 4, Integer.MaxValue) Assert.Equal(&HEF, fileContents(0)) Assert.Equal(&HBB, fileContents(1)) Assert.Equal(&HBF, fileContents(2)) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(733242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/733242")> Public Sub Bug733242() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim xml = dir.CreateFile("a.xml") xml.WriteAllText("EMPTY") Using xmlFileHandle As FileStream = File.Open(xml.ToString(), FileMode.Open, FileAccess.Read, FileShare.Delete Or FileShare.ReadWrite) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc+ {0}", src.ToString()), startFolder:=dir.ToString(), expectedRetCode:=0) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))) Using reader As New StreamReader(xmlFileHandle) Dim content = reader.ReadToEnd() AssertOutput( <text> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> a </name> </assembly> <members> <member name="T:C"> <summary>ABC...XYZ</summary> </member> </members> </doc> ]]> </text>, content) End Using End Using CleanupAllGeneratedFiles(src.Path) CleanupAllGeneratedFiles(xml.Path) End Sub <Fact, WorkItem(768605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768605")> Public Sub Bug768605() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC&lt;/summary&gt; Class C: End Class ''' &lt;summary&gt;XYZ&lt;/summary&gt; Class E: End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim xml = dir.CreateFile("a.xml") xml.WriteAllText("EMPTY") Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc+ {0}", src.ToString()), startFolder:=dir.ToString(), expectedRetCode:=0) AssertOutput(<text></text>, output) Using reader As New StreamReader(xml.ToString()) Dim content = reader.ReadToEnd() AssertOutput( <text> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> a </name> </assembly> <members> <member name="T:C"> <summary>ABC</summary> </member> <member name="T:E"> <summary>XYZ</summary> </member> </members> </doc> ]]> </text>, content) End Using src.WriteAllText( <text> ''' &lt;summary&gt;ABC&lt;/summary&gt; Class C: End Class </text>.Value.Replace(vbLf, vbCrLf)) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc+ {0}", src.ToString()), startFolder:=dir.ToString(), expectedRetCode:=0) AssertOutput(<text></text>, output) Using reader As New StreamReader(xml.ToString()) Dim content = reader.ReadToEnd() AssertOutput( <text> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> a </name> </assembly> <members> <member name="T:C"> <summary>ABC</summary> </member> </members> </doc> ]]> </text>, content) End Using CleanupAllGeneratedFiles(src.Path) CleanupAllGeneratedFiles(xml.Path) End Sub <Fact, WorkItem(705148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705148")> Public Sub Bug705148a() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc:abcdfg.xyz /doc+ {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(705148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705148")> Public Sub Bug705148b() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc /out:MyXml.dll {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "MyXml.xml"))) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(705148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705148")> Public Sub Bug705148c() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc:doc.xml /doc+ {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(705202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705202")> Public Sub Bug705202a() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc:doc.xml /out:out.dll {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml"))) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(705202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705202")> Public Sub Bug705202b() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc:doc.xml /doc /out:out.dll {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "out.xml"))) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(705202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705202")> Public Sub Bug705202c() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /t:library /doc:doc.xml /out:out.dll /doc+ {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "out.xml"))) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(531021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531021")> Public Sub ParseDocBreak2() ' In dev11, if you give an invalid file name, the documentation comments ' are parsed but writing the XML file fails with (warning!) BC42311. Const baseDirectory As String = "C:\abc\def\baz" Dim parsedArgs = DefaultParse({"/doc:"" """, "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments(" ", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) parsedArgs = DefaultParse({"/doc:"" \ """, "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments(" \ ", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' UNC parsedArgs = DefaultParse({"/doc:\\b", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments("\\b", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Even though the format was incorrect ' invalid name: parsedArgs = DefaultParse({"/doc:a.b" + ChrW(0) + "b", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments("a.b" + ChrW(0) + "b", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Even though the format was incorrect parsedArgs = DefaultParse({"/doc:a" + ChrW(55296) + "b.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments("a" + ChrW(55296) + "b.xml", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Even though the format was incorrect parsedArgs = DefaultParse({"/doc:""a<>.xml""", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments("a<>.xml", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Even though the format was incorrect End Sub <Fact> Public Sub ParseDoc() Const baseDirectory As String = "C:\abc\def\baz" Dim parsedArgs = DefaultParse({"/doc:", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("doc", ":<file>")) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) parsedArgs = DefaultParse({"/doc", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) parsedArgs = DefaultParse({"/doc+", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) parsedArgs = DefaultParse({"/doc-", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.None, parsedArgs.ParseOptions.DocumentationMode) parsedArgs = DefaultParse({"/doc+:abc.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("doc")) Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) parsedArgs = DefaultParse({"/doc-:a.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("doc")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.None, parsedArgs.ParseOptions.DocumentationMode) ' Should preserve fully qualified paths parsedArgs = DefaultParse({"/doc:C:\MyFolder\MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\MyFolder\MyBinary.xml", parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Should handle quotes parsedArgs = DefaultParse({"/doc:""C:\My Folder\MyBinary.xml""", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\My Folder\MyBinary.xml", parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Should expand partially qualified paths parsedArgs = DefaultParse({"/doc:MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Should expand partially qualified paths parsedArgs = DefaultParse({"/doc:..\MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\abc\def\MyBinary.xml", parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' drive-relative path: Dim currentDrive As Char = Directory.GetCurrentDirectory()(0) parsedArgs = DefaultParse({"/doc:" + currentDrive + ":a.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments(currentDrive + ":a.xml", "The system cannot find the path specified")) Assert.Null(parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) ' Even though the format was incorrect ' UNC parsedArgs = DefaultParse({"/doc:\\server\share\file.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("\\server\share\file.xml", parsedArgs.DocumentationPath) Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) End Sub <Fact> Public Sub ParseDocAndOut() Const baseDirectory As String = "C:\abc\def\baz" ' Can specify separate directories for binary and XML output. Dim parsedArgs = DefaultParse({"/doc:a\b.xml", "/out:c\d.exe", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\abc\def\baz\a\b.xml", parsedArgs.DocumentationPath) Assert.Equal("C:\abc\def\baz\c", parsedArgs.OutputDirectory) Assert.Equal("d.exe", parsedArgs.OutputFileName) ' XML does not fall back on output directory. parsedArgs = DefaultParse({"/doc:b.xml", "/out:c\d.exe", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\abc\def\baz\b.xml", parsedArgs.DocumentationPath) Assert.Equal("C:\abc\def\baz\c", parsedArgs.OutputDirectory) Assert.Equal("d.exe", parsedArgs.OutputFileName) End Sub <Fact> Public Sub ParseDocMultiple() Const baseDirectory As String = "C:\abc\def\baz" Dim parsedArgs = DefaultParse({"/doc+", "/doc-", "/doc+", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) parsedArgs = DefaultParse({"/doc-", "/doc+", "/doc-", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(DocumentationMode.None, parsedArgs.ParseOptions.DocumentationMode) Assert.Null(parsedArgs.DocumentationPath) parsedArgs = DefaultParse({"/doc:a.xml", "/doc-", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(DocumentationMode.None, parsedArgs.ParseOptions.DocumentationMode) Assert.Null(parsedArgs.DocumentationPath) parsedArgs = DefaultParse({"/doc:abc.xml", "/doc+", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) parsedArgs = DefaultParse({"/doc-", "/doc:a.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) parsedArgs = DefaultParse({"/doc+", "/doc:a.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode) Assert.Equal(Path.Combine(baseDirectory, "a.xml"), parsedArgs.DocumentationPath) End Sub <Fact> Public Sub ParseErrorLog() Const baseDirectory As String = "C:\abc\def\baz" Dim parsedArgs = DefaultParse({"/errorlog:", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) parsedArgs = DefaultParse({"/errorlog", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Should preserve fully qualified paths parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path) Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Should handle quotes parsedArgs = DefaultParse({"/errorlog:""C:\My Folder\MyBinary.xml""", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\My Folder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path) Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Quote after a \ is treated as an escape parsedArgs = DefaultParse({"/errorlog:C:\""My Folder""\MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("C:""My Folder\MyBinary.xml").WithLocation(1, 1)) ' Should expand partially qualified paths parsedArgs = DefaultParse({"/errorlog:MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.ErrorLogOptions.Path) ' Should expand partially qualified paths parsedArgs = DefaultParse({"/errorlog:..\MyBinary.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\abc\def\MyBinary.xml", parsedArgs.ErrorLogOptions.Path) Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' drive-relative path: Dim currentDrive As Char = Directory.GetCurrentDirectory()(0) Dim filePath = currentDrive + ":a.xml" parsedArgs = DefaultParse({"/errorlog:" + filePath, "a.vb"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments(filePath)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' UNC parsedArgs = DefaultParse({"/errorlog:\\server\share\file.xml", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("\\server\share\file.xml", parsedArgs.ErrorLogOptions.Path) Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Parses SARIF version. parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml,version=2", "a.cs"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path) Assert.Equal(SarifVersion.Sarif2, parsedArgs.ErrorLogOptions.SarifVersion) Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Invalid SARIF version. parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml,version=42", "a.cs"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_BadSwitchValue).WithArguments("C:\MyFolder\MyBinary.xml,version=42", "errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml,version=1.0.0", "a.cs"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_BadSwitchValue).WithArguments("C:\MyFolder\MyBinary.xml,version=1.0.0", "errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml,version=2.1.0", "a.cs"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_BadSwitchValue).WithArguments("C:\MyFolder\MyBinary.xml,version=2.1.0", "errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Invalid errorlog qualifier. parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml,invalid=42", "a.cs"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_BadSwitchValue).WithArguments("C:\MyFolder\MyBinary.xml,invalid=42", "errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) ' Too many errorlog qualifiers. parsedArgs = DefaultParse({"/errorlog:C:\MyFolder\MyBinary.xml,version=2,version=2", "a.cs"}, baseDirectory) parsedArgs.Errors.Verify( Diagnostic(ERRID.ERR_BadSwitchValue).WithArguments("C:\MyFolder\MyBinary.xml,version=2,version=2", "errorlog", CommandLineParser.ErrorLogOptionFormat)) Assert.Null(parsedArgs.ErrorLogOptions) Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics) End Sub <Fact> Public Sub ParseErrorLogAndOut() Const baseDirectory As String = "C:\abc\def\baz" ' Can specify separate directories for binary and error log output. Dim parsedArgs = DefaultParse({"/errorlog:a\b.xml", "/out:c\d.exe", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\abc\def\baz\a\b.xml", parsedArgs.ErrorLogOptions.Path) Assert.Equal("C:\abc\def\baz\c", parsedArgs.OutputDirectory) Assert.Equal("d.exe", parsedArgs.OutputFileName) ' error log does not fall back on output directory. parsedArgs = DefaultParse({"/errorlog:b.xml", "/out:c\d.exe", "a.vb"}, baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("C:\abc\def\baz\b.xml", parsedArgs.ErrorLogOptions.Path) Assert.Equal("C:\abc\def\baz\c", parsedArgs.OutputDirectory) Assert.Equal("d.exe", parsedArgs.OutputFileName) End Sub <Fact> Public Sub KeyContainerAndKeyFile() ' KEYCONTAINER Dim parsedArgs = DefaultParse({"/KeyContainer:key-cont-name", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("key-cont-name", parsedArgs.CompilationOptions.CryptoKeyContainer) parsedArgs = DefaultParse({"/KEYcontainer", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keycontainer", ":<string>")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer) parsedArgs = DefaultParse({"/keycontainer-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/keycontainer-")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer) parsedArgs = DefaultParse({"/keycontainer:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keycontainer", ":<string>")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer) parsedArgs = DefaultParse({"/keycontainer: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keycontainer", ":<string>")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer) ' KEYFILE parsedArgs = DefaultParse({"/keyfile:\somepath\s""ome Fil""e.goo.bar", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("\somepath\some File.goo.bar", parsedArgs.CompilationOptions.CryptoKeyFile) parsedArgs = DefaultParse({"/keyFile", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keyfile", ":<file>")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile) parsedArgs = DefaultParse({"/keyfile-", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/keyfile-")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile) parsedArgs = DefaultParse({"/keyfile: ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keyfile", ":<file>")) Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile) ' default value parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Nothing, parsedArgs.CompilationOptions.CryptoKeyContainer) Assert.Equal(Nothing, parsedArgs.CompilationOptions.CryptoKeyFile) ' keyfile/keycontainer conflicts parsedArgs = DefaultParse({"/keycontainer:a", "/keyfile:b", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(Nothing, parsedArgs.CompilationOptions.CryptoKeyContainer) Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyFile) ' keyfile/keycontainer conflicts parsedArgs = DefaultParse({"/keyfile:b", "/keycontainer:a", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyContainer) Assert.Equal(Nothing, parsedArgs.CompilationOptions.CryptoKeyFile) End Sub <Fact, WorkItem(530088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530088")> Public Sub Platform() ' test recognizing all options Dim parsedArgs = DefaultParse({"/platform:X86", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.X86, parsedArgs.CompilationOptions.Platform) parsedArgs = DefaultParse({"/platform:x64", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.X64, parsedArgs.CompilationOptions.Platform) parsedArgs = DefaultParse({"/platform:itanium", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.Itanium, parsedArgs.CompilationOptions.Platform) parsedArgs = DefaultParse({"/platform:anycpu", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.AnyCpu, parsedArgs.CompilationOptions.Platform) parsedArgs = DefaultParse({"/platform:anycpu32bitpreferred", "/t:exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform) parsedArgs = DefaultParse({"/platform:anycpu32bitpreferred", "/t:appcontainerexe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform) parsedArgs = DefaultParse({"/platform:arm", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.Arm, parsedArgs.CompilationOptions.Platform) ' test default (AnyCPU) parsedArgs = DefaultParse({"/debug-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.AnyCpu, parsedArgs.CompilationOptions.Platform) ' test missing parsedArgs = DefaultParse({"/platform:", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("platform", ":<string>")) parsedArgs = DefaultParse({"/platform", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("platform", ":<string>")) parsedArgs = DefaultParse({"/platform+", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/platform+")) ' TODO: Dev11 reports ERR_ArgumentRequired ' test illegal input parsedArgs = DefaultParse({"/platform:abcdef", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("platform", "abcdef")) ' test overriding parsedArgs = DefaultParse({"/platform:anycpu32bitpreferred", "/platform:anycpu", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(CodeAnalysis.Platform.AnyCpu, parsedArgs.CompilationOptions.Platform) ' test illegal parsedArgs = DefaultParse({"/platform:anycpu32bitpreferred", "/t:library", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_LibAnycpu32bitPreferredConflict).WithArguments("Platform", "AnyCpu32BitPreferred").WithLocation(1, 1)) parsedArgs = DefaultParse({"/platform:anycpu", "/platform:anycpu32bitpreferred", "/target:winmdobj", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_LibAnycpu32bitPreferredConflict).WithArguments("Platform", "AnyCpu32BitPreferred").WithLocation(1, 1)) End Sub <Fact()> Public Sub FileAlignment() ' test recognizing all options Dim parsedArgs = DefaultParse({"/filealign:512", "a.vb"}, _baseDirectory) Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:1024", "a.vb"}, _baseDirectory) Assert.Equal(1024, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:2048", "a.vb"}, _baseDirectory) Assert.Equal(2048, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:4096", "a.vb"}, _baseDirectory) Assert.Equal(4096, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:8192", "a.vb"}, _baseDirectory) Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment) ' test oct values parsedArgs = DefaultParse({"/filealign:01000", "a.vb"}, _baseDirectory) Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:02000", "a.vb"}, _baseDirectory) Assert.Equal(1024, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:04000", "a.vb"}, _baseDirectory) Assert.Equal(2048, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:010000", "a.vb"}, _baseDirectory) Assert.Equal(4096, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:020000", "a.vb"}, _baseDirectory) Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment) ' test hex values parsedArgs = DefaultParse({"/filealign:0x200", "a.vb"}, _baseDirectory) Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:0x400", "a.vb"}, _baseDirectory) Assert.Equal(1024, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:0x800", "a.vb"}, _baseDirectory) Assert.Equal(2048, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:0x1000", "a.vb"}, _baseDirectory) Assert.Equal(4096, parsedArgs.EmitOptions.FileAlignment) parsedArgs = DefaultParse({"/filealign:0x2000", "a.vb"}, _baseDirectory) Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment) ' test default (no value) parsedArgs = DefaultParse({"/platform:x86", "a.vb"}, _baseDirectory) Assert.Equal(0, parsedArgs.EmitOptions.FileAlignment) ' test missing parsedArgs = DefaultParse({"/filealign:", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("filealign", ":<number>")) ' test illegal parsedArgs = DefaultParse({"/filealign:0", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("filealign", "0")) parsedArgs = DefaultParse({"/filealign:0x", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("filealign", "0x")) parsedArgs = DefaultParse({"/filealign:0x0", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("filealign", "0x0")) parsedArgs = DefaultParse({"/filealign:-1", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("filealign", "-1")) parsedArgs = DefaultParse({"/filealign:-0x100", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("filealign", "-0x100")) End Sub <Fact()> Public Sub RemoveIntChecks() Dim parsedArgs = DefaultParse({"/removeintcheckS", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.False(parsedArgs.CompilationOptions.CheckOverflow) parsedArgs = DefaultParse({"/removeintcheckS+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.False(parsedArgs.CompilationOptions.CheckOverflow) parsedArgs = DefaultParse({"/removeintcheckS-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.CompilationOptions.CheckOverflow) parsedArgs = DefaultParse({"/removeintchecks+", "/removeintchecks-", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.True(parsedArgs.CompilationOptions.CheckOverflow) parsedArgs = DefaultParse({"/removeintchecks:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("removeintchecks")) parsedArgs = DefaultParse({"/removeintchecks:+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("removeintchecks")) parsedArgs = DefaultParse({"/removeintchecks+:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_SwitchNeedsBool).WithArguments("removeintchecks")) End Sub <Fact()> Public Sub BaseAddress() ' This test is about what passes the parser. Even if a value was accepted by the parser it might not be considered ' as a valid base address later on (e.g. values >0x8000). ' test decimal values being treated as hex Dim parsedArgs = DefaultParse({"/baseaddress:0", "a.vb"}, _baseDirectory) Assert.Equal(CType(0, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:1024", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H1024, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:2048", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H2048, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:4096", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H4096, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:8192", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H8192, ULong), parsedArgs.EmitOptions.BaseAddress) ' test hex values being treated as hex parsedArgs = DefaultParse({"/baseaddress:0x200", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H200, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:0x400", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H400, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:0x800", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H800, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:0x1000", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H1000, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:0xFFFFFFFFFFFFFFFF", "a.vb"}, _baseDirectory) Assert.Equal(ULong.MaxValue, parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:FFFFFFFFFFFFFFFF", "a.vb"}, _baseDirectory) Assert.Equal(ULong.MaxValue, parsedArgs.EmitOptions.BaseAddress) ' test octal values being treated as hex parsedArgs = DefaultParse({"/baseaddress:00", "a.vb"}, _baseDirectory) Assert.Equal(CType(0, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:01024", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H1024, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:02048", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H2048, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:04096", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H4096, ULong), parsedArgs.EmitOptions.BaseAddress) parsedArgs = DefaultParse({"/baseaddress:08192", "a.vb"}, _baseDirectory) Assert.Equal(CType(&H8192, ULong), parsedArgs.EmitOptions.BaseAddress) ' test default (no value) parsedArgs = DefaultParse({"/platform:x86", "a.vb"}, _baseDirectory) Assert.Equal(CType(0, ULong), parsedArgs.EmitOptions.BaseAddress) ' test missing parsedArgs = DefaultParse({"/baseaddress:", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("baseaddress", ":<number>")) ' test illegal parsedArgs = DefaultParse({"/baseaddress:0x10000000000000000", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("baseaddress", "0x10000000000000000")) parsedArgs = DefaultParse({"/BASEADDRESS:-1", "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("baseaddress", "-1")) parsedArgs = DefaultParse({"/BASEADDRESS:" + ULong.MaxValue.ToString, "a.vb"}, _baseDirectory) Verify(parsedArgs.Errors, Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("baseaddress", ULong.MaxValue.ToString)) End Sub <Fact()> Public Sub BinaryFile() Dim binaryPath = Temp.CreateFile().WriteAllBytes(TestMetadata.ResourcesNet451.mscorlib).Path Dim outWriter As New StringWriter() Dim exitCode As Integer = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/preferreduilang:en", binaryPath}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2015: the file '" + binaryPath + "' is not a text file", outWriter.ToString.Trim()) CleanupAllGeneratedFiles(binaryPath) End Sub <Fact()> Public Sub AddModule() Dim parsedArgs = DefaultParse({"/nostdlib", "/vbruntime-", "/addMODULE:c:\,d:\x\y\z,abc,,", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() Assert.Equal(3, parsedArgs.MetadataReferences.Length) Assert.Equal("c:\", parsedArgs.MetadataReferences(0).Reference) Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences(0).Properties.Kind) Assert.Equal("d:\x\y\z", parsedArgs.MetadataReferences(1).Reference) Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences(1).Properties.Kind) Assert.Equal("abc", parsedArgs.MetadataReferences(2).Reference) Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences(2).Properties.Kind) Assert.False(parsedArgs.MetadataReferences(0).Reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)) Assert.False(parsedArgs.MetadataReferences(1).Reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)) Assert.False(parsedArgs.MetadataReferences(2).Reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)) Assert.True(parsedArgs.DefaultCoreLibraryReference.Value.Reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)) Assert.Equal(MetadataImageKind.Assembly, parsedArgs.DefaultCoreLibraryReference.Value.Properties.Kind) parsedArgs = DefaultParse({"/ADDMODULE", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("addmodule", ":<file_list>")) parsedArgs = DefaultParse({"/addmodule:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("addmodule", ":<file_list>")) parsedArgs = DefaultParse({"/addmodule+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/addmodule+")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact()> Public Sub LibPathsAndLibEnvVariable() Dim parsedArgs = DefaultParse({"/libpath:c:\,d:\x\y\z,abc,,", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertReferencePathsEqual(parsedArgs.ReferencePaths, Nothing, "c:\", "d:\x\y\z", Path.Combine(_baseDirectory, "abc")) parsedArgs = DefaultParse({"/lib:c:\Windows", "/libpaths:abc\def, , , ", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertReferencePathsEqual(parsedArgs.ReferencePaths, Nothing, "c:\Windows", Path.Combine(_baseDirectory, "abc\def")) parsedArgs = DefaultParse({"/libpath", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("libpath", ":<path_list>")) parsedArgs = DefaultParse({"/libpath:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("libpath", ":<path_list>")) parsedArgs = DefaultParse({"/libpath+", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/libpath+")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact(), WorkItem(546005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546005")> Public Sub LibPathsAndLibEnvVariable_Relative_vbc() Dim tempFolder = Temp.CreateDirectory() Dim baseDirectory = tempFolder.ToString() Dim subFolder = tempFolder.CreateDirectory("temp") Dim subDirectory = subFolder.ToString() Dim src = Temp.CreateFile("a.vb") src.WriteAllText("Imports System") Dim outWriter As New StringWriter() Dim exitCode As Integer = New MockVisualBasicCompiler(Nothing, subDirectory, {"/nologo", "/t:library", "/out:abc.xyz", src.ToString()}).Run(outWriter, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", outWriter.ToString().Trim()) outWriter = New StringWriter() exitCode = New MockVisualBasicCompiler(Nothing, baseDirectory, {"/nologo", "/libpath:temp", "/r:abc.xyz.dll", "/t:library", src.ToString()}).Run(outWriter, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", outWriter.ToString().Trim()) CleanupAllGeneratedFiles(src.Path) End Sub <Fact()> Public Sub UnableWriteOutput() Dim tempFolder = Temp.CreateDirectory() Dim baseDirectory = tempFolder.ToString() Dim subFolder = tempFolder.CreateDirectory("temp.dll") Dim src = Temp.CreateFile("a.vb") src.WriteAllText("Imports System") Dim outWriter As New StringWriter() Dim exitCode As Integer = New MockVisualBasicCompiler(Nothing, baseDirectory, {"/nologo", "/preferreduilang:en", "/t:library", "/out:" & subFolder.ToString(), src.ToString()}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.True(outWriter.ToString().Contains("error BC2012: can't open '" & subFolder.ToString() & "' for writing: ")) ' Cannot create a file when that file already exists. CleanupAllGeneratedFiles(src.Path) End Sub <Fact()> Public Sub SdkPathAndLibEnvVariable() Dim parsedArgs = DefaultParse({"/libpath:c:lib2", "/sdkpath:<>,d:\sdk1", "/vbruntime*", "/nostdlib", "a.vb"}, _baseDirectory) ' invalid paths are ignored parsedArgs.Errors.Verify() AssertReferencePathsEqual(parsedArgs.ReferencePaths, "d:\sdk1") parsedArgs = DefaultParse({"/sdkpath:c:\Windows", "/sdkpath:d:\Windows", "/vbruntime*", "/nostdlib", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertReferencePathsEqual(parsedArgs.ReferencePaths, "d:\Windows") parsedArgs = DefaultParse({"/sdkpath:c:\Windows,d:\blah", "a.vb"}, _baseDirectory) AssertReferencePathsEqual(parsedArgs.ReferencePaths, "c:\Windows", "d:\blah") parsedArgs = DefaultParse({"/libpath:c:\Windows,d:\blah", "/sdkpath:c:\lib2", "a.vb"}, _baseDirectory) AssertReferencePathsEqual(parsedArgs.ReferencePaths, "c:\lib2", "c:\Windows", "d:\blah") parsedArgs = DefaultParse({"/sdkpath", "/vbruntime*", "/nostdlib", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("sdkpath", ":<path>")) parsedArgs = DefaultParse({"/sdkpath:", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("sdkpath", ":<path>")) parsedArgs = DefaultParse({"/sdkpath+", "/vbruntime*", "/nostdlib", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/sdkpath+")) ' TODO: Dev11 reports ERR_ArgumentRequired End Sub <Fact()> Public Sub VbRuntime() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text> Imports Microsoft.VisualBasic Class C Dim a = vbLf Dim b = Loc End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /vbruntime /t:library " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> src.vb(5) : error BC30455: Argument not specified for parameter 'FileNumber' of 'Public Function Loc(FileNumber As Integer) As Long'. Dim b = Loc ~~~ </text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /vbruntime+ /t:library " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> src.vb(5) : error BC30455: Argument not specified for parameter 'FileNumber' of 'Public Function Loc(FileNumber As Integer) As Long'. Dim b = Loc ~~~ </text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /vbruntime* /t:library /r:System.dll " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> src.vb(5) : error BC30451: 'Loc' is not declared. It may be inaccessible due to its protection level. Dim b = Loc ~~~ </text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /vbruntime+ /vbruntime:abc /vbruntime* /t:library /r:System.dll " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> src.vb(5) : error BC30451: 'Loc' is not declared. It may be inaccessible due to its protection level. Dim b = Loc ~~~ </text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /vbruntime+ /vbruntime:abc /t:library " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> vbc : error BC2017: could not find library 'abc' </text>, output) Dim newVbCore = dir.CreateFile("Microsoft.VisualBasic.dll") newVbCore.WriteAllBytes(File.ReadAllBytes(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "Microsoft.VisualBasic.dll"))) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /vbruntime:" & newVbCore.ToString() & " /t:library " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> src.vb(5) : error BC30455: Argument not specified for parameter 'FileNumber' of 'Public Function Loc(FileNumber As Integer) As Long'. Dim b = Loc ~~~ </text>, output) CleanupAllGeneratedFiles(src.Path) End Sub <WorkItem(997208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997208")> <Fact> Public Sub VbRuntime02() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text> Imports Microsoft.VisualBasic Class C Dim a = vbLf Dim b = Loc End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /r:mscorlib.dll /vbruntime- /t:library /d:_MyType=\""Empty\"" " & src.ToString(), expectedRetCode:=1) AssertOutput( <text> src.vb(2) : warning BC40056: Namespace or type specified in the Imports 'Microsoft.VisualBasic' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports Microsoft.VisualBasic ~~~~~~~~~~~~~~~~~~~~~ src.vb(4) : error BC30451: 'vbLf' is not declared. It may be inaccessible due to its protection level. Dim a = vbLf ~~~~ src.vb(5) : error BC30451: 'Loc' is not declared. It may be inaccessible due to its protection level. Dim b = Loc ~~~ </text>, output) CleanupAllGeneratedFiles(src.Path) End Sub <Fact()> Public Sub VbRuntimeEmbeddedIsIncompatibleWithNetModule() Dim opt = TestOptions.ReleaseModule opt = opt.WithEmbedVbCoreRuntime(True) opt.Errors.Verify(Diagnostic(ERRID.ERR_VBCoreNetModuleConflict)) CreateCompilationWithMscorlib40AndVBRuntime(<compilation><file/></compilation>, opt).GetDiagnostics().Verify(Diagnostic(ERRID.ERR_VBCoreNetModuleConflict)) opt = opt.WithOutputKind(OutputKind.DynamicallyLinkedLibrary) opt.Errors.Verify() CreateCompilationWithMscorlib40AndVBRuntime(<compilation><file/></compilation>, opt).GetDiagnostics().Verify() End Sub <Fact()> Public Sub SdkPathInAction() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text> Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /sdkpath:l:\x /t:library " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text> vbc : error BC2017: could not find library 'Microsoft.VisualBasic.dll' </text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /r:mscorlib.dll /vbruntime- /sdkpath:c:folder /t:library " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text> vbc : error BC2017: could not find library 'mscorlib.dll' </text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /sdkpath:" & dir.Path & " /t:library " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text> vbc : error BC2017: could not find library 'Microsoft.VisualBasic.dll' </text>, output.Replace(dir.Path, "{SDKPATH}")) ' Create 'System.Runtime.dll' Dim sysRuntime = dir.CreateFile("System.Runtime.dll") sysRuntime.WriteAllBytes(File.ReadAllBytes(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "System.Runtime.dll"))) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /sdkpath:" & dir.Path & " /t:library " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text> vbc : error BC2017: could not find library 'Microsoft.VisualBasic.dll' </text>, output.Replace(dir.Path, "{SDKPATH}")) ' trash in 'System.Runtime.dll' sysRuntime.WriteAllBytes({0, 1, 2, 3, 4, 5}) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /sdkpath:" & dir.Path & " /t:library " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text> vbc : error BC2017: could not find library 'Microsoft.VisualBasic.dll' </text>, output.Replace(dir.Path, "{SDKPATH}")) ' Create 'mscorlib.dll' Dim msCorLib = dir.CreateFile("mscorlib.dll") msCorLib.WriteAllBytes(File.ReadAllBytes(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "mscorlib.dll"))) ' NOT: both libraries exist, but 'System.Runtime.dll' is invalid, so we need to pick up 'mscorlib.dll' output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /nostdlib /sdkpath:" & dir.Path & " /t:library /vbruntime* /r:" & Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "System.dll") & " " & src.ToString(), startFolder:=dir.Path) AssertOutput(<text></text>, output.Replace(dir.Path, "{SDKPATH}")) ' SUCCESSFUL BUILD with 'mscorlib.dll' and embedded VbCore File.Delete(sysRuntime.Path) ' NOTE: only 'mscorlib.dll' exists output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /nostdlib /sdkpath:" & dir.Path & " /t:library /vbruntime* /r:" & Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "System.dll") & " " & src.ToString(), startFolder:=dir.Path) AssertOutput(<text></text>, output.Replace(dir.Path, "{SDKPATH}")) File.Delete(msCorLib.Path) CleanupAllGeneratedFiles(src.Path) End Sub <WorkItem(598158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598158")> <Fact()> Public Sub MultiplePathsInSdkPath() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text> Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output As String = "" Dim subFolder1 = dir.CreateDirectory("fldr1") Dim subFolder2 = dir.CreateDirectory("fldr2") Dim sdkMultiPath = subFolder1.Path & "," & subFolder2.Path Dim cmd As String = " /nologo /preferreduilang:en /sdkpath:" & sdkMultiPath & " /t:library /r:" & Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "System.dll") & " " & src.ToString() Dim cmdNoStdLibNoRuntime As String = "/nostdlib /vbruntime* /r:mscorlib.dll /preferreduilang:en" & cmd ' NOTE: no 'mscorlib.dll' exists output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, cmdNoStdLibNoRuntime, startFolder:=dir.Path, expectedRetCode:=1) AssertOutput(<text>vbc : error BC2017: could not find library 'mscorlib.dll'</text>, output.Replace(dir.Path, "{SDKPATH}")) ' Create '<dir>\fldr2\mscorlib.dll' Dim msCorLib = subFolder2.CreateFile("mscorlib.dll") msCorLib.WriteAllBytes(File.ReadAllBytes(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "mscorlib.dll"))) ' NOTE: only 'mscorlib.dll' exists output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, cmdNoStdLibNoRuntime, startFolder:=dir.Path) AssertOutput(<text></text>, output.Replace(dir.Path, "{SDKPATH}")) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, cmd, startFolder:=dir.Path, expectedRetCode:=1) AssertOutput( <text> vbc : warning BC40049: Could not find standard library 'System.dll'. vbc : error BC2017: could not find library 'Microsoft.VisualBasic.dll' </text>, output.Replace(dir.Path, "{SDKPATH}")) File.Delete(msCorLib.Path) CleanupAllGeneratedFiles(src.Path) End Sub <Fact()> Public Sub NostdlibInAction() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text> Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /t:library " & src.ToString(), startFolder:=dir.Path, expectedRetCode:=1) Assert.Contains("error BC30002: Type 'Global.System.ComponentModel.EditorBrowsable' is not defined.", output, StringComparison.Ordinal) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /nostdlib /define:_MYTYPE=\""Empty\"" /t:library " & src.ToString(), startFolder:=dir.Path) AssertOutput(<text></text>, output) output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /nostdlib /sdkpath:x:\ /vbruntime- /define:_MYTYPE=\""Empty\"" /t:library " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text> src.vb(2) : error BC30002: Type 'System.Void' is not defined. Class C ~~~~~~~ End Class ~~~~~~~~~ src.vb(2) : error BC31091: Import of type 'Object' from assembly or module 'src.dll' failed. Class C ~ </text>, output) CleanupAllGeneratedFiles(src.Path) End Sub Private Sub AssertOutput(expected As XElement, output As String, Optional fileName As String = "src.vb") AssertOutput(expected.Value, output, fileName) End Sub Private Sub AssertOutput(expected As String, output As String, Optional fileName As String = "src.vb") output = Regex.Replace(output, "^.*" & fileName, fileName, RegexOptions.Multiline) output = Regex.Replace(output, "\r\n\s*\r\n", vbCrLf) ' empty strings output = output.Trim() Assert.Equal(expected.Replace(vbLf, vbCrLf).Trim, output) End Sub <Fact()> Public Sub ResponsePathInSearchPath() Dim file = Temp.CreateDirectory().CreateFile("vb.rsp") file.WriteAllText("") Dim parsedArgs = DefaultParse({"/libpath:c:\lib2,", "@" & file.ToString(), "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() AssertReferencePathsEqual(parsedArgs.ReferencePaths, Nothing, Path.GetDirectoryName(file.ToString()), "c:\lib2") CleanupAllGeneratedFiles(file.Path) End Sub Private Sub AssertReferencePathsEqual(refPaths As ImmutableArray(Of String), sdkPathOrNothing As String, ParamArray paths() As String) Assert.Equal(1 + paths.Length, refPaths.Length) Assert.Equal(If(sdkPathOrNothing, RuntimeEnvironment.GetRuntimeDirectory()), refPaths(0)) For i = 0 To paths.Count - 1 Assert.Equal(paths(i), refPaths(i + 1)) Next End Sub <Fact()> Public Sub HighEntropyVirtualAddressSpace() Dim parsedArgs = DefaultParse({"/highentropyva", "a.vb"}, _baseDirectory) Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace) parsedArgs = DefaultParse({"/highentropyva+", "a.vb"}, _baseDirectory) Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace) parsedArgs = DefaultParse({"/highentropyva-", "a.vb"}, _baseDirectory) Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace) parsedArgs = DefaultParse({"/highentropyva:+", "a.vb"}, _baseDirectory) Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace) Verify(parsedArgs.Errors, Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/highentropyva:+")) parsedArgs = DefaultParse({"/highentropyva:", "a.vb"}, _baseDirectory) Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace) Verify(parsedArgs.Errors, Diagnostic(ERRID.WRN_BadSwitch).WithArguments("/highentropyva:")) parsedArgs = DefaultParse({"/highentropyva+ /highentropyva-", "a.vb"}, _baseDirectory) Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace) End Sub <Fact> Public Sub Win32ResQuotes() Dim responseFile As String() = { " /win32resource:d:\\""abc def""\a""b c""d\a.res" } Dim args = DefaultParse(VisualBasicCommandLineParser.ParseResponseLines(responseFile), "c:\") Assert.Equal("d:\abc def\ab cd\a.res", args.Win32ResourceFile) responseFile = { " /win32icon:d:\\""abc def""\a""b c""d\a.ico" } args = DefaultParse(VisualBasicCommandLineParser.ParseResponseLines(responseFile), "c:\") Assert.Equal("d:\abc def\ab cd\a.ico", args.Win32Icon) responseFile = { " /win32manifest:d:\\""abc def""\a""b c""d\a.manifest" } args = DefaultParse(VisualBasicCommandLineParser.ParseResponseLines(responseFile), "c:\") Assert.Equal("d:\abc def\ab cd\a.manifest", args.Win32Manifest) End Sub <Fact> Public Sub ResourceOnlyCompile() Dim parsedArgs = DefaultParse({"/resource:goo.vb,ed", "/out:e.dll"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/resource:goo.vb,ed"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_NoSourcesOut)) End Sub <Fact> Public Sub OutputFileName1() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from name of first file. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:library"}, expectedOutputName:="p.dll") End Sub <Fact> Public Sub OutputFileName2() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:library", "/out:r.dll"}, expectedOutputName:="r.dll") End Sub <Fact> Public Sub OutputFileName3() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from name of first file. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:exe"}, expectedOutputName:="p.exe") End Sub <Fact> Public Sub OutputFileName4() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:exe", "/out:r.exe"}, expectedOutputName:="r.exe") End Sub <Fact> Public Sub OutputFileName5() Dim source1 = <![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from name of first file. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:exe", "/main:A"}, expectedOutputName:="p.exe") End Sub <Fact> Public Sub OutputFileName6() Dim source1 = <![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from name of first file. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:exe", "/main:B"}, expectedOutputName:="p.exe") End Sub <WorkItem(545773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545773")> <Fact> Public Sub OutputFileName7() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:library", "/out:goo"}, expectedOutputName:="goo.dll") End Sub <WorkItem(545773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545773")> <Fact> Public Sub OutputFileName8() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:library", "/out:goo. "}, expectedOutputName:="goo.dll") End Sub <WorkItem(545773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545773")> <Fact> Public Sub OutputFileName9() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:library", "/out:goo.a"}, expectedOutputName:="goo.a.dll") End Sub <WorkItem(545773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545773")> <Fact> Public Sub OutputFileName10() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:module", "/out:goo.a"}, expectedOutputName:="goo.a") End Sub <WorkItem(545773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545773")> <Fact> Public Sub OutputFileName11() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:module", "/out:goo.a . . . . "}, expectedOutputName:="goo.a") End Sub <WorkItem(545773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545773")> <Fact> Public Sub OutputFileName12() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:module", "/out:goo. . . . . "}, expectedOutputName:="goo.netmodule") End Sub <Fact> Public Sub OutputFileName13() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from name of first file. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:winmdobj"}, expectedOutputName:="p.winmdobj") End Sub <Fact> Public Sub OutputFileName14() Dim source1 = <![CDATA[ Class A End Class ]]> Dim source2 = <![CDATA[ Class B Shared Sub Main() End Sub End Class ]]> ' Name comes from name of first file. CheckOutputFileName( source1, source2, inputName1:="p.cs", inputName2:="q.cs", commandLineArguments:={"/target:appcontainerexe"}, expectedOutputName:="p.exe") End Sub Private Sub CheckOutputFileName(source1 As XCData, source2 As XCData, inputName1 As String, inputName2 As String, commandLineArguments As String(), expectedOutputName As String) Dim dir = Temp.CreateDirectory() Dim file1 = dir.CreateFile(inputName1) file1.WriteAllText(source1.Value) Dim file2 = dir.CreateFile(inputName2) file2.WriteAllText(source2.Value) Dim outWriter As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, commandLineArguments.Concat({inputName1, inputName2}).ToArray()) Dim exitCode As Integer = vbc.Run(outWriter, Nothing) If exitCode <> 0 Then Console.WriteLine(outWriter.ToString()) Assert.Equal(0, exitCode) End If Assert.Equal(1, Directory.EnumerateFiles(dir.Path, "*" & PathUtilities.GetExtension(expectedOutputName)).Count()) Assert.Equal(1, Directory.EnumerateFiles(dir.Path, expectedOutputName).Count()) If System.IO.File.Exists(expectedOutputName) Then System.IO.File.Delete(expectedOutputName) End If CleanupAllGeneratedFiles(file1.Path) CleanupAllGeneratedFiles(file2.Path) End Sub Private Shared Sub AssertSpecificDiagnostics(expectedCodes As Integer(), expectedOptions As ReportDiagnostic(), args As VisualBasicCommandLineArguments) Dim actualOrdered = args.CompilationOptions.SpecificDiagnosticOptions.OrderBy(Function(entry) entry.Key) AssertEx.Equal( expectedCodes.Select(Function(i) MessageProvider.Instance.GetIdForErrorCode(i)), actualOrdered.Select(Function(entry) entry.Key)) AssertEx.Equal(expectedOptions, actualOrdered.Select(Function(entry) entry.Value)) End Sub <Fact> Public Sub WarningsOptions() ' Baseline Dim parsedArgs = DefaultParse({"a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors parsedArgs = DefaultParse({"/warnaserror", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors+ parsedArgs = DefaultParse({"/warnaserror+", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors: parsedArgs = DefaultParse({"/warnaserror:", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors:42024,42025 parsedArgs = DefaultParse({"/warnaserror:42024,42025", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) AssertSpecificDiagnostics({42024, 42025}, {ReportDiagnostic.Error, ReportDiagnostic.Error}, parsedArgs) ' Test for /warnaserrors+: parsedArgs = DefaultParse({"/warnaserror+:", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors+:42024,42025 parsedArgs = DefaultParse({"/warnaserror+:42024,42025", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) AssertSpecificDiagnostics({42024, 42025}, {ReportDiagnostic.Error, ReportDiagnostic.Error}, parsedArgs) ' Test for /warnaserrors- parsedArgs = DefaultParse({"/warnaserror-", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors-: parsedArgs = DefaultParse({"/warnaserror-:", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /warnaserrors-:42024,42025 parsedArgs = DefaultParse({"/warnaserror-:42024,42025", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) AssertSpecificDiagnostics({42024, 42025}, {ReportDiagnostic.Default, ReportDiagnostic.Default}, parsedArgs) ' Test for /nowarn parsedArgs = DefaultParse({"/nowarn", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Suppress, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /nowarn: parsedArgs = DefaultParse({"/nowarn:", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) ' Test for /nowarn:42024,42025 parsedArgs = DefaultParse({"/nowarn:42024,42025", "a.vb"}, _baseDirectory) Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption) AssertSpecificDiagnostics({42024, 42025}, {ReportDiagnostic.Suppress, ReportDiagnostic.Suppress}, parsedArgs) End Sub <Fact()> Public Sub WarningsErrors() ' Previous versions of the compiler used to report warnings (BC2026, BC2014) ' whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. ' We no longer generate a warning in such cases. ' Test for /warnaserrors:1 Dim parsedArgs = DefaultParse({"/warnaserror:1", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() ' Test for /warnaserrors:abc parsedArgs = DefaultParse({"/warnaserror:abc", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() ' Test for /nowarn:1 parsedArgs = DefaultParse({"/nowarn:1", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() ' Test for /nowarn:abc parsedArgs = DefaultParse({"/nowarn:abc", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify() End Sub <WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")> <Fact()> Public Sub CompilationWithWarnAsError() Dim source = <![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> ' Baseline without warning options (expect success) Dim exitCode As Integer = GetExitCode(source.Value, "a.vb", {}) Assert.Equal(0, exitCode) ' The case with /warnaserror (expect to be success, since there will be no warning) exitCode = GetExitCode(source.Value, "b.vb", {"/warnaserror"}) Assert.Equal(0, exitCode) ' The case with /warnaserror and /nowarn:1 (expect success) ' Note that even though the command line option has a warning, it is not going to become an error ' in order to avoid the halt of compilation. exitCode = GetExitCode(source.Value, "c.vb", {"/warnaserror", "/nowarn:1"}) Assert.Equal(0, exitCode) End Sub Public Function GetExitCode(source As String, fileName As String, commandLineArguments As String()) As Integer Dim dir = Temp.CreateDirectory() Dim file1 = dir.CreateFile(fileName) file1.WriteAllText(source) Dim outWriter As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, commandLineArguments.Concat({fileName}).ToArray()) Return vbc.Run(outWriter, Nothing) End Function <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_01() Dim source = <compilation> <file name="a.vb">Imports System Module Program Sub Main(args As String()) Dim x As Integer Dim yy As Integer Const zzz As Long = 0 End Sub Function goo() End Function End Module </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(5) : warning BC42024: Unused local variable: 'x'. Dim x As Integer ~ PATH(6) : warning BC42024: Unused local variable: 'yy'. Dim yy As Integer ~~ PATH(7) : warning BC42099: Unused local constant: 'zzz'. Const zzz As Long = 0 ~~~ PATH(11) : warning BC42105: Function 'goo' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Dim expected = ReplacePathAndVersionAndHash(result, file).Trim() Dim actual = output.ToString().Trim() Assert.Equal(expected, actual) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_02() ' It verifies the case where diagnostic does not have the associated location in it. Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices Module Module1 Delegate Sub delegateType() Sub main() Dim a As ArgIterator = Nothing Dim d As delegateType = AddressOf a.Goo End Sub <Extension()> _ Public Function Goo(ByVal x As ArgIterator) as Integer Return 1 End Function End Module ]]> </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(9) : error BC36640: Instance of restricted type 'ArgIterator' cannot be used in a lambda expression. Dim d As delegateType = AddressOf a.Goo ~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en", "-imports:System"}) vbc.Run(output, Nothing) Assert.Equal(ReplacePathAndVersionAndHash(result, file), output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_03() ' It verifies the case where the squiggles covers the error span with tabs in it. Dim source = "Module Module1" + vbCrLf + " Sub Main()" + vbCrLf + " Dim x As Integer = ""a" + vbTab + vbTab + vbTab + "b""c ' There is a tab in the string." + vbCrLf + " End Sub" + vbCrLf + "End Module" + vbCrLf Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(3) : error BC30201: Expression expected. Dim x As Integer = "a b"c ' There is a tab in the string. ~ PATH(3) : error BC30004: Character constant must contain exactly one character. Dim x As Integer = "a b"c ' There is a tab in the string. ~~~~~~~~~~~~~~~~~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Dim expected = ReplacePathAndVersionAndHash(result, file).Trim() Dim actual = output.ToString().Trim() Assert.Equal(expected, actual) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_04() ' It verifies the case where the squiggles covers multiple lines. Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Collections.Generic Module Module1 Sub Main() Dim i3 = From el In { 3, 33, 333 } Select el End Sub End Module ]]> </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(5) : error BC36593: Expression of type 'Integer()' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider. Dim i3 = From el In { ~ 3, 33, 333 ~~~~~~~~~~~~~~~~~~~~~~~~~~ } Select el ~~~~~~~~~~~~~~~~~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Assert.Equal(ReplacePathAndVersionAndHash(result, file), output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_05() ' It verifies the case where the squiggles covers multiple lines. Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Collections.Generic Module _ Module1 Sub Main() End Sub 'End Module ]]> </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(3) : error BC30625: 'Module' statement must end with a matching 'End Module'. Module _ ~~~~~~~~ Module1 ~~~~~~~~~~~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Assert.Equal(ReplacePathAndVersionAndHash(result, file), output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_06() ' It verifies the case where the squiggles covers the very long error span. Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Module Program Event eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee() Event eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee() Sub Main(args As String()) End Sub End Module ]]> </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(7) : error BC37220: Name 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeEventHandler' exceeds the maximum length allowed in metadata. Event eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Assert.Equal(ReplacePathAndVersionAndHash(result, file), output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545214")> <Fact()> Public Sub ErrorMessageWithSquiggles_07() ' It verifies the case where the error is on the last line. Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() Console.WriteLine("Hello from VB") End Sub End Class]]> </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(4) : error BC30625: 'Module' statement must end with a matching 'End Module'. Module Module1 ~~~~~~~~~~~~~~ PATH(8) : error BC30460: 'End Class' must be preceded by a matching 'Class'. End Class ~~~~~~~~~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Assert.Equal(ReplacePathAndVersionAndHash(result, file), output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(531606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531606")> <Fact()> Public Sub ErrorMessageWithSquiggles_08() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() Dim i As system.Boolean, End Sub End Module ]]> </file> </compilation> Dim result = <file name="output">Microsoft (R) Visual Basic Compiler version VERSION (HASH) Copyright (C) Microsoft Corporation. All rights reserved. PATH(6) : error BC30203: Identifier expected. Dim i As system.Boolean, ~ </file> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en"}) vbc.Run(output, Nothing) Assert.Equal(ReplacePathAndVersionAndHash(result, file), output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub Private Shared Function ReplacePathAndVersionAndHash(result As XElement, file As TempFile) As String Return result.Value.Replace("PATH", file.Path).Replace("VERSION (HASH)", s_compilerVersion).Replace(vbLf, vbCrLf) End Function <WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")> <Fact()> Public Sub CompilationWithNonExistingOutPath() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/target:exe", "/preferreduilang:en", "/out:sub\a.exe"}) Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC2012: can't open '" + dir.Path + "\sub\a.exe' for writing", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")> <Fact()> Public Sub CompilationWithWrongOutPath_01() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en", "/target:exe", "/out:sub\"}) Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Dim message = output.ToString() Assert.Contains("error BC2032: File name", message, StringComparison.Ordinal) Assert.Contains("sub", message, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")> <Fact()> Public Sub CompilationWithWrongOutPath_02() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en", "/target:exe", "/out:sub\ "}) Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Dim message = output.ToString() Assert.Contains("error BC2032: File name", message, StringComparison.Ordinal) Assert.Contains("sub", message, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")> <Fact()> Public Sub CompilationWithWrongOutPath_03() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en", "/target:exe", "/out:aaa:\a.exe"}) Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC2032: File name 'aaa:\a.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")> <Fact()> Public Sub CompilationWithWrongOutPath_04() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, "/preferreduilang:en", "/target:exe", "/out: "}) Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC2006: option 'out' requires ':<file>'", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <Fact()> Public Sub SpecifyProperCodePage() ' Class <UTF8 Cyrillic Character> ' End Class Dim source() As Byte = { &H43, &H6C, &H61, &H73, &H73, &H20, &HD0, &H96, &HD, &HA, &H45, &H6E, &H64, &H20, &H43, &H6C, &H61, &H73, &H73 } Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllBytes(source) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /t:library " & file.ToString(), startFolder:=dir.Path) Assert.Equal("", output) ' Autodetected UTF8, NO ERROR output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /preferreduilang:en /t:library /codepage:20127 " & file.ToString(), expectedRetCode:=1, startFolder:=dir.Path) ' 20127: US-ASCII ' 0xd0, 0x96 ==> 'Ж' ==> ERROR Dim expected = <result> a.vb(1) : error BC30203: Identifier expected. Class ?? ~ </result>.Value.Replace(vbLf, vbCrLf).Trim() Dim actual = Regex.Replace(output, "^.*a.vb", "a.vb", RegexOptions.Multiline).Trim() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub EmittedSubsystemVersion() Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText( <text> Class C End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim comp = VisualBasicCompilation.Create("a.dll", options:=TestOptions.ReleaseDll) Dim peHeaders = New PEHeaders(comp.EmitToStream(New EmitOptions(subsystemVersion:=SubsystemVersion.Create(5, 1)))) Assert.Equal(5, peHeaders.PEHeader.MajorSubsystemVersion) Assert.Equal(1, peHeaders.PEHeader.MinorSubsystemVersion) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub DefaultManifestForExe() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim expectedManifest = <?xml version="1.0" encoding="utf-16"?> <ManifestResource Size="490"> <Contents><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource> CheckManifestXml(source, OutputKind.ConsoleApplication, explicitManifest:=Nothing, expectedManifest:=expectedManifest) End Sub <Fact> Public Sub DefaultManifestForDll() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> CheckManifestXml(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest:=Nothing, expectedManifest:=Nothing) End Sub <Fact> Public Sub DefaultManifestForModule() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> CheckManifestXml(source, OutputKind.NetModule, explicitManifest:=Nothing, expectedManifest:=Nothing) End Sub <Fact> Public Sub DefaultManifestForWinExe() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim expectedManifest = <?xml version="1.0" encoding="utf-16"?> <ManifestResource Size="490"> <Contents><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource> CheckManifestXml(source, OutputKind.WindowsApplication, explicitManifest:=Nothing, expectedManifest:=expectedManifest) End Sub <Fact> Public Sub DefaultManifestForAppContainerExe() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim expectedManifest = <?xml version="1.0" encoding="utf-16"?> <ManifestResource Size="490"> <Contents><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource> CheckManifestXml(source, OutputKind.WindowsRuntimeApplication, explicitManifest:=Nothing, expectedManifest:=expectedManifest) End Sub <Fact> Public Sub DefaultManifestForWinMDObj() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> CheckManifestXml(source, OutputKind.WindowsRuntimeMetadata, explicitManifest:=Nothing, expectedManifest:=Nothing) End Sub <Fact> Public Sub ExplicitManifestForExe() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim explicitManifest = <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="Test.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> Dim expectedManifest = <?xml version="1.0" encoding="utf-16"?> <ManifestResource Size="421"> <Contents><![CDATA[<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="Test.app" /> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource> CheckManifestXml(source, OutputKind.ConsoleApplication, explicitManifest, expectedManifest) End Sub <Fact> Public Sub ExplicitManifestResForDll() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim explicitManifest = <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="Test.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> Dim expectedManifest = <?xml version="1.0" encoding="utf-16"?> <ManifestResource Size="421"> <Contents><![CDATA[<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="Test.app" /> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource> CheckManifestXml(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest, expectedManifest) End Sub <Fact> Public Sub ExplicitManifestForModule() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim explicitManifest = <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" name="Test.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> CheckManifestXml(source, OutputKind.NetModule, explicitManifest, expectedManifest:=Nothing) End Sub <DllImport("kernel32.dll", SetLastError:=True)> Public Shared Function _ LoadLibraryEx(lpFileName As String, hFile As IntPtr, dwFlags As UInteger) As IntPtr End Function <DllImport("kernel32.dll", SetLastError:=True)> Public Shared Function _ FreeLibrary(hFile As IntPtr) As Boolean End Function Private Sub CheckManifestXml(source As XElement, outputKind As OutputKind, explicitManifest As XDocument, expectedManifest As XDocument) Dim dir = Temp.CreateDirectory() Dim sourceFile = dir.CreateFile("Test.cs").WriteAllText(source.Value) Dim outputFileName As String Dim target As String Select Case outputKind Case OutputKind.ConsoleApplication outputFileName = "Test.exe" target = "exe" Case OutputKind.WindowsApplication outputFileName = "Test.exe" target = "winexe" Case OutputKind.DynamicallyLinkedLibrary outputFileName = "Test.dll" target = "library" Case OutputKind.NetModule outputFileName = "Test.netmodule" target = "module" Case OutputKind.WindowsRuntimeMetadata outputFileName = "Test.winmdobj" target = "winmdobj" Case OutputKind.WindowsRuntimeApplication outputFileName = "Test.exe" target = "appcontainerexe" Case Else Throw TestExceptionUtilities.UnexpectedValue(outputKind) End Select Dim vbc As VisualBasicCompiler Dim manifestFile As TempFile If explicitManifest Is Nothing Then vbc = New MockVisualBasicCompiler(Nothing, dir.Path, { String.Format("/target:{0}", target), String.Format("/out:{0}", outputFileName), Path.GetFileName(sourceFile.Path) }) Else manifestFile = dir.CreateFile("Test.config").WriteAllText(explicitManifest.ToString()) vbc = New MockVisualBasicCompiler(Nothing, dir.Path, { String.Format("/target:{0}", target), String.Format("/out:{0}", outputFileName), String.Format("/win32manifest:{0}", Path.GetFileName(manifestFile.Path)), Path.GetFileName(sourceFile.Path) }) End If Assert.Equal(0, vbc.Run(New StringWriter(), Nothing)) Dim library As IntPtr = LoadLibraryEx(Path.Combine(dir.Path, outputFileName), IntPtr.Zero, 2) If library = IntPtr.Zero Then Throw New Win32Exception(Marshal.GetLastWin32Error()) End If Const resourceType As String = "#24" Dim resourceId As String = If(outputKind = OutputKind.DynamicallyLinkedLibrary, "#2", "#1") Dim manifestSize As UInteger = Nothing If expectedManifest Is Nothing Then Assert.Throws(Of Win32Exception)(Function() Win32Res.GetResource(library, resourceId, resourceType, manifestSize)) Else Dim manifestResourcePointer As IntPtr = Win32Res.GetResource(library, resourceId, resourceType, manifestSize) Dim actualManifest As String = Win32Res.ManifestResourceToXml(manifestResourcePointer, manifestSize) Assert.Equal(expectedManifest.ToString(), XDocument.Parse(actualManifest).ToString()) End If FreeLibrary(library) CleanupAllGeneratedFiles(sourceFile.Path) End Sub <WorkItem(530221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530221")> <WorkItem(5664, "https://github.com/dotnet/roslyn/issues/5664")> <ConditionalFact(GetType(IsEnglishLocal))> Public Sub Bug15538() ' The icacls command fails on our Helix machines And it appears to be related to the use of the $ in ' the username. ' https://github.com/dotnet/roslyn/issues/28836 If StringComparer.OrdinalIgnoreCase.Equals(Environment.UserDomainName, "WORKGROUP") Then Return End If Dim folder = Temp.CreateDirectory() Dim source As String = folder.CreateFile("src.vb").WriteAllText("").Path Dim ref As String = folder.CreateFile("ref.dll").WriteAllText("").Path Try Dim output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " & ref & " /inheritance:r /Q") Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()) output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " & ref & " /deny %USERDOMAIN%\%USERNAME%:(r,WDAC) /Q") Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()) output = ProcessUtilities.RunAndGetOutput("cmd", "/C """ & s_basicCompilerExecutable & """ /nologo /preferreduilang:en /r:" & ref & " /t:library " & source, expectedRetCode:=1) Assert.True(output.StartsWith("vbc : error BC31011: Unable to load referenced library '" & ref & "': Access to the path '" & ref & "' is denied.", StringComparison.Ordinal)) Finally Dim output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " & ref & " /reset /Q") Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()) File.Delete(ref) End Try CleanupAllGeneratedFiles(source) End Sub <WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")> <Fact()> Public Sub ResponseFilesWithNoconfig_01() Dim source As String = Temp.CreateFile().WriteAllText(<text> Imports System Module Module1 Sub Main() Dim x As Integer End Sub End Module </text>.Value).Path Dim rsp As String = Temp.CreateFile().WriteAllText(<text> /warnaserror </text>.Value).Path ' Checks the base case without /noconfig (expect to see error) Dim vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en"}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC42024: Unused local variable: 'x'.", output.ToString(), StringComparison.Ordinal) ' Checks the base case with /noconfig (expect to see warning, instead of error) vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en", "/noconfig"}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC42024: Unused local variable: 'x'.", output.ToString(), StringComparison.Ordinal) ' Checks the base case with /NOCONFIG (expect to see warning, instead of error) vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en", "/NOCONFIG"}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC42024: Unused local variable: 'x'.", output.ToString(), StringComparison.Ordinal) ' Checks the base case with -noconfig (expect to see warning, instead of error) vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en", "-noconfig"}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC42024: Unused local variable: 'x'.", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(rsp) End Sub <WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")> <Fact()> Public Sub ResponseFilesWithNoconfig_02() Dim source As String = Temp.CreateFile().WriteAllText(<text> Imports System Module Module1 Sub Main() End Sub End Module </text>.Value).Path Dim rsp As String = Temp.CreateFile().WriteAllText(<text> /noconfig </text>.Value).Path ' Checks the case with /noconfig inside the response file (expect to see warning) Dim vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en"}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC2025: ignoring /noconfig option because it was specified in a response file", output.ToString(), StringComparison.Ordinal) ' Checks the case with /noconfig inside the response file as along with /nowarn (expect to see warning) vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en", "/nowarn"}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC2025: ignoring /noconfig option because it was specified in a response file", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(rsp) End Sub <WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")> <Fact()> Public Sub ResponseFilesWithNoconfig_03() Dim source As String = Temp.CreateFile().WriteAllText(<text> Imports System Module Module1 Sub Main() End Sub End Module </text>.Value).Path Dim rsp As String = Temp.CreateFile().WriteAllText(<text> /NOCONFIG </text>.Value).Path ' Checks the case with /noconfig inside the response file (expect to see warning) Dim vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en"}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC2025: ignoring /noconfig option because it was specified in a response file", output.ToString(), StringComparison.Ordinal) ' Checks the case with /NOCONFIG inside the response file as along with /nowarn (expect to see warning) vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en", "/nowarn"}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC2025: ignoring /noconfig option because it was specified in a response file", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(rsp) End Sub <WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")> <Fact()> Public Sub ResponseFilesWithNoconfig_04() Dim source As String = Temp.CreateFile().WriteAllText(<text> Imports System Module Module1 Sub Main() End Sub End Module </text>.Value).Path Dim rsp As String = Temp.CreateFile().WriteAllText(<text> -noconfig </text>.Value).Path ' Checks the case with /noconfig inside the response file (expect to see warning) Dim vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en"}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC2025: ignoring /noconfig option because it was specified in a response file", output.ToString(), StringComparison.Ordinal) ' Checks the case with -noconfig inside the response file as along with /nowarn (expect to see warning) vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en", "/nowarn"}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Contains("warning BC2025: ignoring /noconfig option because it was specified in a response file", output.ToString(), StringComparison.Ordinal) CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(rsp) End Sub <WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")> <Fact()> Public Sub ResponseFilesWithEmptyAliasReference() Dim source As String = Temp.CreateFile().WriteAllText(<text> Imports System </text>.Value).Path Dim rsp As String = Temp.CreateFile().WriteAllText(<text> -nologo /r:a="""" </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(rsp, _baseDirectory, {source, "/preferreduilang:en"}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2017: could not find library 'a='", output.ToString().Trim()) CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(rsp) End Sub <WorkItem(546031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546031")> <WorkItem(546032, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546032")> <WorkItem(546033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546033")> <Fact()> Public Sub InvalidDefineSwitch() Dim source As String = Temp.CreateFile().WriteAllText(<text> Imports System </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define", source}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'define' requires ':<symbol_list>'", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'define' requires ':<symbol_list>'", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define: ", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC2006: option 'define' requires ':<symbol_list>'", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:_,", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant '_ ^^ ^^ ' is not valid: Identifier expected.", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:_a,", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:_ a,", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant '_ ^^ ^^ a' is not valid: Identifier expected.", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:a,_,b", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant '_ ^^ ^^ ' is not valid: Identifier expected.", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:_", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant '_ ^^ ^^ ' is not valid: Identifier expected.", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:_ ", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant '_ ^^ ^^ ' is not valid: Identifier expected.", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"-nologo", "/preferreduilang:en", "/t:libraRY", "/define:a,_", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant '_ ^^ ^^ ' is not valid: Identifier expected.", output.ToString().Trim()) CleanupAllGeneratedFiles(source) End Sub Private Function GetDefaultResponseFilePath() As String Return Temp.CreateFile().WriteAllBytes(GetType(CommandLineTests).Assembly.GetManifestResourceStream("vbc.rsp").ReadAllBytes()).Path End Function <Fact> Public Sub DefaultResponseFile() Dim defaultResponseFile = GetDefaultResponseFilePath() Assert.True(File.Exists(defaultResponseFile)) Dim vbc As New MockVisualBasicCompiler(defaultResponseFile, _baseDirectory, {}) ' VB includes these by default, with or without the default response file. Dim corlibLocation = GetType(Object).Assembly.Location Dim corlibDir = Path.GetDirectoryName(corlibLocation) Dim systemLocation = Path.Combine(corlibDir, "System.dll") Dim msvbLocation = Path.Combine(corlibDir, "Microsoft.VisualBasic.dll") Assert.Equal(vbc.Arguments.MetadataReferences.Select(Function(r) r.Reference), { "Accessibility.dll", "System.Configuration.dll", "System.Configuration.Install.dll", "System.Data.dll", "System.Data.OracleClient.dll", "System.Deployment.dll", "System.Design.dll", "System.DirectoryServices.dll", "System.dll", "System.Drawing.Design.dll", "System.Drawing.dll", "System.EnterpriseServices.dll", "System.Management.dll", "System.Messaging.dll", "System.Runtime.Remoting.dll", "System.Runtime.Serialization.Formatters.Soap.dll", "System.Security.dll", "System.ServiceProcess.dll", "System.Transactions.dll", "System.Web.dll", "System.Web.Mobile.dll", "System.Web.RegularExpressions.dll", "System.Web.Services.dll", "System.Windows.Forms.dll", "System.XML.dll", "System.Workflow.Activities.dll", "System.Workflow.ComponentModel.dll", "System.Workflow.Runtime.dll", "System.Runtime.Serialization.dll", "System.ServiceModel.dll", "System.Core.dll", "System.Xml.Linq.dll", "System.Data.Linq.dll", "System.Data.DataSetExtensions.dll", "System.Web.Extensions.dll", "System.Web.Extensions.Design.dll", "System.ServiceModel.Web.dll", systemLocation, msvbLocation }, StringComparer.OrdinalIgnoreCase) Assert.Equal(vbc.Arguments.CompilationOptions.GlobalImports.Select(Function(i) i.Name), { "System", "Microsoft.VisualBasic", "System.Linq", "System.Xml.Linq" }) Assert.True(vbc.Arguments.CompilationOptions.OptionInfer) End Sub <Fact> Public Sub DefaultResponseFileNoConfig() Dim defaultResponseFile = GetDefaultResponseFilePath() Assert.True(File.Exists(defaultResponseFile)) Dim vbc As New MockVisualBasicCompiler(defaultResponseFile, _baseDirectory, {"/noconfig"}) ' VB includes these by default, with or without the default response file. Dim corlibLocation = GetType(Object).Assembly.Location Dim corlibDir = Path.GetDirectoryName(corlibLocation) Dim systemLocation = Path.Combine(corlibDir, "System.dll") Dim msvbLocation = Path.Combine(corlibDir, "Microsoft.VisualBasic.dll") Assert.Equal(vbc.Arguments.MetadataReferences.Select(Function(r) r.Reference), { systemLocation, msvbLocation }, StringComparer.OrdinalIgnoreCase) Assert.Equal(0, vbc.Arguments.CompilationOptions.GlobalImports.Count) Assert.False(vbc.Arguments.CompilationOptions.OptionInfer) End Sub <Fact(), WorkItem(546114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546114")> Public Sub TestFilterCommandLineDiagnostics() Dim source As String = Temp.CreateFile().WriteAllText(<text> Module Module1 Function blah() As Integer End Function Sub Main() End Sub End Module </text>.Value).Path ' Previous versions of the compiler used to report warnings (BC2026) ' whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. ' We no longer generate a warning in such cases. Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/preferreduilang:en", "/blah", "/nowarn:2007,42353,1234,2026", source}) Dim output = New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("vbc : warning BC2007: unrecognized option '/blah'; ignored", output.ToString().Trim()) CleanupAllGeneratedFiles(source) End Sub <WorkItem(546305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546305")> <Fact()> Public Sub Bug15539() Dim source As String = Temp.CreateFile().WriteAllText(<text> Module Module1 Sub Main() End Sub End Module </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/preferreduilang:en", "/define:I(", source}) Dim output As New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant 'I ^^ ^^ ' is not valid: End of statement expected.", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/preferreduilang:en", "/define:I*", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Equal("vbc : error BC31030: Conditional compilation constant 'I ^^ ^^ ' is not valid: End of statement expected.", output.ToString().Trim()) End Sub <Fact()> Public Sub TestImportsWithQuotes() Dim errors As IEnumerable(Of DiagnosticInfo) = Nothing Dim [imports] = "System,""COLL = System.Collections"",System.Diagnostics,""COLLGEN = System.Collections.Generic""" Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/imports:" + [imports]}) Assert.Equal(4, vbc.Arguments.CompilationOptions.GlobalImports.Count) Assert.Equal("System", vbc.Arguments.CompilationOptions.GlobalImports(0).Name) Assert.Equal("COLL = System.Collections", vbc.Arguments.CompilationOptions.GlobalImports(1).Name) Assert.Equal("System.Diagnostics", vbc.Arguments.CompilationOptions.GlobalImports(2).Name) Assert.Equal("COLLGEN = System.Collections.Generic", vbc.Arguments.CompilationOptions.GlobalImports(3).Name) End Sub <Fact()> Public Sub TestCommandLineSwitchThatNoLongerAreImplemented() ' These switches are no longer implemented and should fail silently ' the switches have various arguments that can be used Dim source As String = Temp.CreateFile().WriteAllText(<text> Module Module1 Sub Main() End Sub End Module </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/netcf", source}) Dim output = New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/bugreport", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/bugreport:test.dmp", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/errorreport", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/errorreport:prompt", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/errorreport:queue", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/errorreport:send", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/errorreport:", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/bugreport:", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/novbruntimeref", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) ' Just to confirm case insensitive vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/errorreport:PROMPT", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) Assert.Equal("", output.ToString().Trim()) CleanupAllGeneratedFiles(source) End Sub <WorkItem(531263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531263")> <Fact> Public Sub EmptyFileName() Dim outWriter As New StringWriter() Dim exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {""}).Run(outWriter, Nothing) Assert.NotEqual(0, exitCode) ' error BC2032: File name '' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Assert.Contains("BC2032", outWriter.ToString(), StringComparison.Ordinal) End Sub <WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")> <Fact> Public Sub PreferredUILang() Dim outWriter As New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Contains("BC2006", outWriter.ToString(), StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Contains("BC2006", outWriter.ToString(), StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:zz"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Contains("BC2038", outWriter.ToString(), StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:en-zz"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.Contains("BC2038", outWriter.ToString(), StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:en-US"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.DoesNotContain("BC2038", outWriter.ToString(), StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:de"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.DoesNotContain("BC2038", outWriter.ToString(), StringComparison.Ordinal) outWriter = New StringWriter(CultureInfo.InvariantCulture) exitCode = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/preferreduilang:de-AT"}).Run(outWriter, Nothing) Assert.Equal(1, exitCode) Assert.DoesNotContain("BC2038", outWriter.ToString(), StringComparison.Ordinal) End Sub <Fact, WorkItem(650083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650083")> Public Sub ReservedDeviceNameAsFileName() ' Source file name Dim parsedArgs = DefaultParse({"/t:library", "con.vb"}, _baseDirectory) parsedArgs.Errors.Verify() parsedArgs = DefaultParse({"/out:com1.exe", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("\\.\com1").WithLocation(1, 1)) parsedArgs = DefaultParse({"/doc:..\lpt2.xml", "a.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_XMLCannotWriteToXMLDocFile2).WithArguments("..\lpt2.xml", "The system cannot find the path specified").WithLocation(1, 1)) parsedArgs = DefaultParse({"/SdkPath:..\aux", "com.vb"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.WRN_CannotFindStandardLibrary1).WithArguments("System.dll").WithLocation(1, 1), Diagnostic(ERRID.ERR_LibNotFound).WithArguments("Microsoft.VisualBasic.dll").WithLocation(1, 1)) End Sub <Fact()> Public Sub ReservedDeviceNameAsFileName2() Dim source As String = Temp.CreateFile().WriteAllText(<text> Module Module1 Sub Main() End Sub End Module </text>.Value).Path ' Make sure these reserved device names don't affect compiler Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/r:.\com3.dll", "/preferreduilang:en", source}) Dim output = New StringWriter() Dim exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC2017: could not find library '.\com3.dll'", output.ToString(), StringComparison.Ordinal) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/preferreduilang:en", "/link:prn.dll", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC2017: could not find library 'prn.dll'", output.ToString(), StringComparison.Ordinal) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"@aux.rsp", "/preferreduilang:en", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Dim errMessage = output.ToString().Trim() Assert.Contains("error BC2011: unable to open response file", errMessage, StringComparison.Ordinal) Assert.Contains("aux.rsp", errMessage, StringComparison.Ordinal) vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/nologo", "/preferreduilang:en", "/vbruntime:..\con.dll", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(1, exitCode) Assert.Contains("error BC2017: could not find library '..\con.dll'", output.ToString(), StringComparison.Ordinal) ' Native VB compiler also ignore invalid lib paths vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/LibPath:lpt1,Lpt2,LPT9", source}) output = New StringWriter() exitCode = vbc.Run(output, Nothing) Assert.Equal(0, exitCode) CleanupAllGeneratedFiles(source) End Sub <Fact, WorkItem(574361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/574361")> Public Sub LangVersionForOldBC36716() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("src.vb") src.WriteAllText( <text><![CDATA[ Imports System.Runtime.CompilerServices Imports System.Collections Friend Module AutoPropAttributesmod Class AttrInThisAsmAttribute Inherits Attribute Public Property Prop() As Integer End Class Class HasProps <CompilerGenerated()> Public Property Scen1() As <CompilerGenerated()> Func(Of String) <CLSCompliant(False), Obsolete("obsolete message!")> <AttrInThisAsmAttribute()> Public Property Scen2() As String End Class End Module ]]> </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, "/nologo /t:library /langversion:9 /preferreduilang:en " & src.ToString(), expectedRetCode:=1, startFolder:=dir.Path) AssertOutput( <text><![CDATA[ src.vb(8) : error BC36716: Visual Basic 9.0 does not support auto-implemented properties. Public Property Prop() As Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ src.vb(12) : error BC36716: Visual Basic 9.0 does not support auto-implemented properties. <CompilerGenerated()> ~~~~~~~~~~~~~~~~~~~~~ Public Property Scen1() As <CompilerGenerated()> Func(Of String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ src.vb(12) : error BC36716: Visual Basic 9.0 does not support implicit line continuation. <CompilerGenerated()> ~~~~~~~~~~~~~~~~~~~~~ Public Property Scen1() As <CompilerGenerated()> Func(Of String) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ src.vb(14) : error BC36716: Visual Basic 9.0 does not support auto-implemented properties. <CLSCompliant(False), Obsolete("obsolete message!")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <AttrInThisAsmAttribute()> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Public Property Scen2() As String ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ src.vb(14) : error BC36716: Visual Basic 9.0 does not support implicit line continuation. <CLSCompliant(False), Obsolete("obsolete message!")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <AttrInThisAsmAttribute()> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Public Property Scen2() As String ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </text>, output) CleanupAllGeneratedFiles(src.Path) End Sub <Fact> Public Sub DiagnosticFormatting() Dim source = " Class C Sub Main() Goo(0) #ExternalSource(""c:\temp\a\1.vb"", 10) Goo(1) #End ExternalSource #ExternalSource(""C:\a\..\b.vb"", 20) Goo(2) #End ExternalSource #ExternalSource(""C:\a\../B.vb"", 30) Goo(3) #End ExternalSource #ExternalSource(""../b.vb"", 40) Goo(4) #End ExternalSource #ExternalSource(""..\b.vb"", 50) Goo(5) #End ExternalSource #ExternalSource(""C:\X.vb"", 60) Goo(6) #End ExternalSource #ExternalSource(""C:\x.vb"", 70) Goo(7) #End ExternalSource #ExternalSource("" "", 90) Goo(9) #End ExternalSource #ExternalSource(""C:\*.vb"", 100) Goo(10) #End ExternalSource #ExternalSource("""", 110) Goo(11) #End ExternalSource Goo(12) #ExternalSource(""***"", 140) Goo(14) #End ExternalSource End Sub End Class " Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb").WriteAllText(source) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/preferreduilang:en", "/t:library", "a.vb"}) Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) ' with /fullpaths off Dim expected = file.Path & "(4) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(0) ~~~ c:\temp\a\1.vb(10) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(1) ~~~ C:\b.vb(20) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(2) ~~~ C:\B.vb(30) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(3) ~~~ " & Path.GetFullPath(Path.Combine(dir.Path, "..\b.vb")) & "(40) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(4) ~~~ " & Path.GetFullPath(Path.Combine(dir.Path, "..\b.vb")) & "(50) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(5) ~~~ C:\X.vb(60) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(6) ~~~ C:\x.vb(70) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(7) ~~~ (90) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(9) ~~~ C:\*.vb(100) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(10) ~~~ (110) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(11) ~~~ " & file.Path & "(35) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(12) ~~~ ***(140) : error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level. Goo(14) ~~~ " AssertOutput(expected.Replace(vbCrLf, vbLf), outWriter.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <Fact> Public Sub ParseFeatures() Dim args = DefaultParse({"/features:Test", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal("Test", args.ParseOptions.Features.Single().Key) args = DefaultParse({"/features:Test", "a.vb", "/Features:Experiment"}, _baseDirectory) args.Errors.Verify() Assert.Equal(2, args.ParseOptions.Features.Count) Assert.True(args.ParseOptions.Features.ContainsKey("Test")) Assert.True(args.ParseOptions.Features.ContainsKey("Experiment")) args = DefaultParse({"/features:Test=false,Key=value", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.ParseOptions.Features.SetEquals(New Dictionary(Of String, String) From {{"Test", "false"}, {"Key", "value"}})) ' We don't do any rigorous validation of /features arguments... args = DefaultParse({"/features", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Empty(args.ParseOptions.Features) args = DefaultParse({"/features:Test,", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.True(args.ParseOptions.Features.SetEquals(New Dictionary(Of String, String) From {{"Test", "true"}})) End Sub <Fact> Public Sub ParseAdditionalFile() Dim args = DefaultParse({"/additionalfile:web.config", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles.Single().Path) args = DefaultParse({"/additionalfile:web.config", "a.vb", "/additionalfile:app.manifest"}, _baseDirectory) args.Errors.Verify() Assert.Equal(2, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles(0).Path) Assert.Equal(Path.Combine(_baseDirectory, "app.manifest"), args.AdditionalFiles(1).Path) args = DefaultParse({"/additionalfile:web.config", "a.vb", "/additionalfile:web.config"}, _baseDirectory) args.Errors.Verify() Assert.Equal(2, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles(0).Path) Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles(1).Path) args = DefaultParse({"/additionalfile:..\web.config", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(Path.Combine(_baseDirectory, "..\web.config"), args.AdditionalFiles.Single().Path) Dim baseDir = Temp.CreateDirectory() baseDir.CreateFile("web1.config") baseDir.CreateFile("web2.config") baseDir.CreateFile("web3.config") args = DefaultParse({"/additionalfile:web*.config", "a.vb"}, baseDir.Path) args.Errors.Verify() Assert.Equal(3, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(baseDir.Path, "web1.config"), args.AdditionalFiles(0).Path) Assert.Equal(Path.Combine(baseDir.Path, "web2.config"), args.AdditionalFiles(1).Path) Assert.Equal(Path.Combine(baseDir.Path, "web3.config"), args.AdditionalFiles(2).Path) args = DefaultParse({"/additionalfile:web.config;app.manifest", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(2, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles(0).Path) Assert.Equal(Path.Combine(_baseDirectory, "app.manifest"), args.AdditionalFiles(1).Path) args = DefaultParse({"/additionalfile:web.config,app.manifest", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(2, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles(0).Path) Assert.Equal(Path.Combine(_baseDirectory, "app.manifest"), args.AdditionalFiles(1).Path) args = DefaultParse({"/additionalfile:""web.config,app.manifest""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(1, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config,app.manifest"), args.AdditionalFiles(0).Path) args = DefaultParse({"/additionalfile:\""web.config,app.manifest\""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(1, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config,app.manifest"), args.AdditionalFiles(0).Path) args = DefaultParse({"/additionalfile:\""""web.config,app.manifest""\""", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(2, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config"), args.AdditionalFiles(0).Path) Assert.Equal(Path.Combine(_baseDirectory, "app.manifest"), args.AdditionalFiles(1).Path) args = DefaultParse({"/additionalfile:web.config:app.manifest", "a.vb"}, _baseDirectory) args.Errors.Verify() Assert.Equal(1, args.AdditionalFiles.Length) Assert.Equal(Path.Combine(_baseDirectory, "web.config:app.manifest"), args.AdditionalFiles(0).Path) args = DefaultParse({"/additionalfile", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("additionalfile", ":<file_list>")) Assert.Equal(0, args.AdditionalFiles.Length) args = DefaultParse({"/additionalfile:", "a.vb"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("additionalfile", ":<file_list>")) Assert.Equal(0, args.AdditionalFiles.Length) End Sub <Fact> Public Sub ParseEditorConfig() Dim args = DefaultParse({"/analyzerconfig:.editorconfig", "a.vb"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig"), args.AnalyzerConfigPaths.Single()) args = DefaultParse({"/analyzerconfig:.editorconfig", "a.vb", "/analyzerconfig:subdir\.editorconfig"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(2, args.AnalyzerConfigPaths.Length) Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig"), args.AnalyzerConfigPaths(0)) Assert.Equal(Path.Combine(_baseDirectory, "subdir\.editorconfig"), args.AnalyzerConfigPaths(1)) args = DefaultParse({"/analyzerconfig:.editorconfig", "a.vb", "/analyzerconfig:.editorconfig"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(2, args.AnalyzerConfigPaths.Length) Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig"), args.AnalyzerConfigPaths(0)) Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig"), args.AnalyzerConfigPaths(1)) args = DefaultParse({"/analyzerconfig:..\.editorconfig", "a.vb"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(Path.Combine(_baseDirectory, "..\.editorconfig"), args.AnalyzerConfigPaths.Single()) args = DefaultParse({"/analyzerconfig:.editorconfig;subdir\.editorconfig", "a.vb"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(2, args.AnalyzerConfigPaths.Length) Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig"), args.AnalyzerConfigPaths(0)) Assert.Equal(Path.Combine(_baseDirectory, "subdir\.editorconfig"), args.AnalyzerConfigPaths(1)) args = DefaultParse({"/analyzerconfig:.editorconfig,subdir\.editorconfig", "a.vb"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(2, args.AnalyzerConfigPaths.Length) Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig"), args.AnalyzerConfigPaths(0)) Assert.Equal(Path.Combine(_baseDirectory, "subdir\.editorconfig"), args.AnalyzerConfigPaths(1)) args = DefaultParse({"/analyzerconfig:.editorconfig:.editorconfig", "a.vb"}, _baseDirectory) args.Errors.AssertNoErrors() Assert.Equal(1, args.AnalyzerConfigPaths.Length) Assert.Equal(Path.Combine(_baseDirectory, ".editorconfig:.editorconfig"), args.AnalyzerConfigPaths(0)) args = DefaultParse({"/analyzerconfig", "a.vb"}, _baseDirectory) args.Errors.AssertTheseDiagnostics( <errors><![CDATA[ BC2006: option 'analyzerconfig' requires ':<file_list>' ]]> </errors>) Assert.Equal(0, args.AnalyzerConfigPaths.Length) args = DefaultParse({"/analyzerconfig:", "a.vb"}, _baseDirectory) args.Errors.AssertTheseDiagnostics( <errors><![CDATA[ BC2006: option 'analyzerconfig' requires ':<file_list>']]> </errors>) Assert.Equal(0, args.AnalyzerConfigPaths.Length) End Sub Private Shared Sub Verify(actual As IEnumerable(Of Diagnostic), ParamArray expected As DiagnosticDescription()) actual.Verify(expected) End Sub Private Const s_logoLine1 As String = "Microsoft (R) Visual Basic Compiler version" Private Const s_logoLine2 As String = "Copyright (C) Microsoft Corporation. All rights reserved." Private Shared Function OccurrenceCount(source As String, word As String) As Integer Dim n = 0 Dim index = source.IndexOf(word, StringComparison.Ordinal) While (index >= 0) n += 1 index = source.IndexOf(word, index + word.Length, StringComparison.Ordinal) End While Return n End Function Private Shared Function VerifyOutput(sourceDir As TempDirectory, sourceFile As TempFile, Optional includeCurrentAssemblyAsAnalyzerReference As Boolean = True, Optional additionalFlags As String() = Nothing, Optional expectedInfoCount As Integer = 0, Optional expectedWarningCount As Integer = 0, Optional expectedErrorCount As Integer = 0, Optional errorlog As Boolean = False, Optional analyzers As ImmutableArray(Of DiagnosticAnalyzer) = Nothing) As String Dim args = { "/nologo", "/preferreduilang:en", "/t:library", sourceFile.Path } If includeCurrentAssemblyAsAnalyzerReference Then args = args.Append("/a:" + Assembly.GetExecutingAssembly().Location) End If If errorlog Then args = args.Append("/errorlog:errorlog") End If If additionalFlags IsNot Nothing Then args = args.Append(additionalFlags) End If Dim vbc = New MockVisualBasicCompiler(Nothing, sourceDir.Path, args, analyzers) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = vbc.Run(outWriter, Nothing) Dim output = outWriter.ToString() Dim expectedExitCode = If(expectedErrorCount > 0, 1, 0) Assert.True(expectedExitCode = exitCode, String.Format("Expected exit code to be '{0}' was '{1}'.{2}Output:{3}{4}", expectedExitCode, exitCode, Environment.NewLine, Environment.NewLine, output)) Assert.DoesNotContain(" : hidden", output, StringComparison.Ordinal) If expectedInfoCount = 0 Then Assert.DoesNotContain(" : info", output, StringComparison.Ordinal) Else ' Info diagnostics are only logged with /errorlog. Assert.True(errorlog) Assert.Equal(expectedInfoCount, OccurrenceCount(output, " : info")) End If If expectedWarningCount = 0 Then Assert.DoesNotContain(" : warning", output, StringComparison.Ordinal) Else Assert.Equal(expectedWarningCount, OccurrenceCount(output, " : warning")) End If If expectedErrorCount = 0 Then Assert.DoesNotContain(" : error", output, StringComparison.Ordinal) Else Assert.Equal(expectedErrorCount, OccurrenceCount(output, " : error")) End If Return output End Function <WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")> <Fact> Public Sub NoWarnAndWarnAsError_AnalyzerDriverWarnings() ' This assembly has an abstract MockAbstractDiagnosticAnalyzer type which should cause ' compiler warning BC42376 to be produced when compilations created in this test try to load it. Dim source = "Imports System" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim output = VerifyOutput(dir, file, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that compiler warning BC42376 can be suppressed via /nowarn. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn"}) ' TEST: Verify that compiler warning BC42376 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:BC42376"}) ' TEST: Verify that compiler warning BC42376 can be promoted to an error via /warnaserror+. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+"}, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' TEST: Verify that compiler warning BC42376 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:42376"}, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")> <WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")> <Fact> Public Sub NoWarnAndWarnAsError_HiddenDiagnostic() ' This assembly has a HiddenDiagnosticAnalyzer type which should produce custom hidden ' diagnostics for #ExternalSource directives present in the compilations created in this test. Dim source = "Imports System #ExternalSource (""file"", 123) #End ExternalSource" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim output = VerifyOutput(dir, file, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn"}) ' TEST: Verify that /nowarn: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /warnaserror+ has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/nowarn:42376"}) ' TEST: Verify that /warnaserror- has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /warnaserror: promotes custom hidden diagnostic Hidden01 to an error. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:hidden01"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify that /warnaserror-: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:Hidden01", "/nowarn:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:hidden01", "/warnaserror:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Hidden01", "/nowarn:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:hidden01", "/warnaserror-:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn doesn't override /warnaserror: in the case of custom hidden diagnostics. ' Although the compiler normally suppresses printing of hidden diagnostics in the compiler output, they are never really suppressed ' because in the IDE features that rely on hidden diagnostics to display light bulb need to continue to work even when users have global ' suppression (/nowarn) specified in their project. In other words, /nowarn flag is a no-op for hidden diagnostics. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/warnaserror:Hidden01"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify /nowarn doesn't override /warnaserror: in the case of custom hidden diagnostics. ' Although the compiler normally suppresses printing of hidden diagnostics in the compiler output, they are never really suppressed ' because in the IDE features that rely on hidden diagnostics to display light bulb need to continue to work even when users have global ' suppression (/nowarn) specified in their project. In other words, /nowarn flag is a no-op for hidden diagnostics. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:HIDDen01", "/nowarn"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify /nowarn and /warnaserror-: have no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Hidden01", "/nowarn"}) ' TEST: Verify /nowarn and /warnaserror-: have no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/warnaserror-:Hidden01"}) ' TEST: Sanity test for /nowarn and /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/nowarn:Hidden01"}) ' TEST: Sanity test for /nowarn and /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:Hidden01", "/nowarn"}) ' TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:Hidden01", "/warnaserror-:hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Hidden01", "/warnaserror+:hidden01"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/warnaserror+:hidden01"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:hiddEn01", "/warnaserror+", "/nowarn:42376"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:HiDden01", "/warnaserror-"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/warnaserror-:Hidden01", "/nowarn:42376"}) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/warnaserror-:Hidden01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Hidden01", "/warnaserror-"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:HiDden01", "/warnaserror+", "/nowarn:42376"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/warnaserror+:HiDden01", "/nowarn:42376"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Hidden01: Throwing a diagnostic for #ExternalSource", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")> <WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")> <WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")> <CombinatorialData, Theory> Public Sub NoWarnAndWarnAsError_InfoDiagnostic(errorlog As Boolean) ' NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. ' This assembly has an InfoDiagnosticAnalyzer type which should produce custom info ' diagnostics for the #Enable directives present in the compilations created in this test. Dim source = "Imports System #Enable Warning" Dim name = "a.vb" Dim output = GetOutput(name, source, expectedWarningCount:=1, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that custom info diagnostic Info01 can be suppressed via /nowarn. output = GetOutput(name, source, additionalFlags:={"/nowarn"}, errorlog:=errorlog) ' TEST: Verify that custom info diagnostic Info01 can be individually suppressed via /nowarn:. output = GetOutput(name, source, additionalFlags:={"/nowarn:Info01"}, expectedWarningCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that custom info diagnostic Info01 can never be promoted to an error via /warnaserror+. output = GetOutput(name, source, additionalFlags:={"/warnaserror+", "/nowarn:42376"}, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that custom info diagnostic Info01 is still reported as an info when /warnaserror- is used. output = GetOutput(name, source, additionalFlags:={"/warnaserror-"}, expectedWarningCount:=1, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that custom info diagnostic Info01 can be individually promoted to an error via /warnaserror:. output = GetOutput(name, source, additionalFlags:={"/warnaserror:info01"}, expectedWarningCount:=1, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) ' TEST: Verify that custom info diagnostic Info01 is still reported as an info when passed to /warnaserror-:. output = GetOutput(name, source, additionalFlags:={"/warnaserror-:info01"}, expectedWarningCount:=1, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify /nowarn: overrides /warnaserror:. output = GetOutput(name, source, additionalFlags:={"/warnaserror:Info01", "/nowarn:info01"}, expectedWarningCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror:. output = GetOutput(name, source, additionalFlags:={"/nowarn:INFO01", "/warnaserror:Info01"}, expectedWarningCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror-:. output = GetOutput(name, source, additionalFlags:={"/warnaserror-:Info01", "/nowarn:info01"}, expectedWarningCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn: overrides /warnaserror-:. output = GetOutput(name, source, additionalFlags:={"/nowarn:INFO01", "/warnaserror-:Info01"}, expectedWarningCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify /nowarn overrides /warnaserror:. output = GetOutput(name, source, additionalFlags:={"/nowarn", "/warnaserror:Info01"}, errorlog:=errorlog) ' TEST: Verify /nowarn overrides /warnaserror:. output = GetOutput(name, source, additionalFlags:={"/warnaserror:Info01", "/nowarn"}, errorlog:=errorlog) ' TEST: Verify /nowarn overrides /warnaserror-:. output = GetOutput(name, source, additionalFlags:={"/nowarn", "/warnaserror-:Info01"}, errorlog:=errorlog) ' TEST: Verify /nowarn overrides /warnaserror-:. output = GetOutput(name, source, additionalFlags:={"/warnaserror-:Info01", "/nowarn"}, errorlog:=errorlog) ' TEST: Sanity test for /nowarn and /nowarn:. output = GetOutput(name, source, additionalFlags:={"/nowarn", "/nowarn:Info01"}, errorlog:=errorlog) ' TEST: Sanity test for /nowarn and /nowarn:. output = GetOutput(name, source, additionalFlags:={"/nowarn:Info01", "/nowarn"}, errorlog:=errorlog) ' TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags:={"/warnaserror+:Info01", "/warnaserror-:info01"}, expectedWarningCount:=1, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags:={"/warnaserror-:Info01", "/warnaserror+:INfo01"}, expectedWarningCount:=1, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror-", "/warnaserror+:info01"}, expectedWarningCount:=1, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror+:InFo01", "/warnaserror+", "/nowarn:42376"}, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror+:InfO01", "/warnaserror-"}, expectedWarningCount:=1, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror+", "/warnaserror-:INfo01", "/nowarn:42376"}, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror-", "/warnaserror-:INfo01"}, expectedWarningCount:=1, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror-:Info01", "/warnaserror-"}, expectedWarningCount:=1, expectedInfoCount:=If(errorlog, 1, 0), errorlog:=errorlog) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) If errorlog Then Assert.Contains("a.vb(2) : info Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End If ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror+", "/warnaserror+:Info01", "/nowarn:42376"}, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = GetOutput(name, source, additionalFlags:={"/warnaserror+:InFO01", "/warnaserror+", "/nowarn:42376"}, expectedErrorCount:=1, errorlog:=errorlog) Assert.Contains("a.vb(2) : error Info01: Throwing a diagnostic for #Enable", output, StringComparison.Ordinal) End Sub Private Function GetOutput(name As String, source As String, Optional includeCurrentAssemblyAsAnalyzerReference As Boolean = True, Optional additionalFlags As String() = Nothing, Optional expectedInfoCount As Integer = 0, Optional expectedWarningCount As Integer = 0, Optional expectedErrorCount As Integer = 0, Optional errorlog As Boolean = False) As String Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(name) file.WriteAllText(source) Dim output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference, additionalFlags, expectedInfoCount, expectedWarningCount, expectedErrorCount, errorlog) CleanupAllGeneratedFiles(file.Path) Return output End Function <WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")> <WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")> <WorkItem(998069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998069")> <WorkItem(998724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998724")> <Fact> Public Sub NoWarnAndWarnAsError_WarningDiagnostic() ' This assembly has a WarningDiagnosticAnalyzer type which should produce custom warning ' diagnostics for source types present in the compilations created in this test. Dim source = "Imports System Module Module1 Sub Main Dim x as Integer End Sub End Module" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim output = VerifyOutput(dir, file, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that compiler warning BC42024 as well as custom warning diagnostics Warning01 and Warning03 can be suppressed via /nowarn. ' This doesn't work for BC42376 currently (Bug 899050). output = VerifyOutput(dir, file, additionalFlags:={"/nowarn"}) ' TEST: Verify that compiler warning BC42024 as well as custom warning diagnostics Warning01 and Warning03 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that compiler warning BC42024 as well as custom warning diagnostics Warning01 and Warning03 can be promoted to errors via /warnaserror. ' Promoting compiler warning BC42024 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror"}, expectedWarningCount:=0, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' TEST: Verify that compiler warning BC42024 as well as custom warning diagnostics Warning01 and Warning03 can be promoted to errors via /warnaserror+. ' This doesn't work correctly currently - promoting compiler warning BC42024 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+"}, expectedWarningCount:=0, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /warnaserror- keeps compiler warning BC42024 as well as custom warning diagnostics Warning01 and Warning03 as warnings. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that custom warning diagnostics Warning01 and Warning03 can be individually promoted to errors via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:warning01,Something,warning03"}, expectedWarningCount:=2, expectedErrorCount:=2) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that compiler warning BC42024 can be individually promoted to an error via /warnaserror+:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:bc42024"}, expectedWarningCount:=3, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : error BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that custom warning diagnostics Warning01 and Warning03 as well as compiler warning BC42024 can be individually promoted to errors via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1, expectedErrorCount:=3) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : error BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that last flag on command line wins between /nowarn and /warnaserror. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror", "/nowarn"}) ' TEST: Verify that last flag on command line wins between /nowarn and /warnaserror+. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/warnaserror+"}, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/warnaserror-"}) ' TEST: Verify that /nowarn overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/nowarn"}) ' TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:Something,042024,Warning01,Warning03", "/nowarn:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000", "/warnaserror:Something,042024,Warning01,Warning03"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Something,042024,Warning01,Warning03", "/nowarn:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000", "/warnaserror-:Something,042024,Warning01,Warning03"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/nowarn:warning01,Warning03,bc42024,58000,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000,42376", "/warnaserror"}) ' TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/nowarn:warning01,Warning03,bc42024,58000,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000,42376", "/warnaserror-"}) ' TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:warning01,Warning03,bc42024,58000", "/nowarn:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000", "/warnaserror-:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/warnaserror:Something,042024,Warning01,Warning03,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:warning01,Warning03,bc42024,58000,42376", "/warnaserror"}) ' TEST: Verify that /nowarn overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Something,042024,Warning01,Warning03,42376", "/nowarn"}) ' TEST: Verify that /nowarn overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/warnaserror-:Something,042024,Warning01,Warning03,42376"}) ' TEST: Sanity test for /nowarn and /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn", "/nowarn:Something,042024,Warning01,Warning03,42376"}) ' TEST: Sanity test for /nowarn: and /nowarn. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:Something,042024,Warning01,Warning03,42376", "/nowarn"}) ' TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/warnaserror+"}, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' Note: Old native compiler behaved strangely for the below case. ' When /warnaserror+ and /warnaserror- appeared on the same command line, native compiler would allow /warnaserror+ to win always ' regardless of order. However when /warnaserror+:xyz and /warnaserror-:xyz appeared on the same command line, native compiler ' would allow the flag that appeared last on the command line to win. Roslyn compiler allows the last flag that appears on the ' command line to win in both cases. This is not a breaking change since at worst this only makes a case that used to be an error ' in the native compiler to be a warning in Roslyn. ' TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/warnaserror-"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:warning01,Warning03", "/warnaserror+:Warning01,Warning03"}, expectedWarningCount:=2, expectedErrorCount:=2) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:Warning01,Warning03", "/warnaserror-:warning01,Warning03"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:warning01,Warning03,bc42024,58000,42376", "/warnaserror+"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:warning01,Warning03,58000", "/warnaserror-"}, expectedWarningCount:=2, expectedErrorCount:=2) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/warnaserror+:warning01,Warning03,bc42024,58000"}, expectedWarningCount:=1, expectedErrorCount:=3) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : error BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/warnaserror-:warning01,Warning03,bc42024,58000,42376"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/warnaserror+:warning01,Warning03,bc42024,58000,42376"}, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:warning01,Warning03,bc42024,58000,42376", "/warnaserror"}, expectedErrorCount:=1) Assert.Contains("error BC42376", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/warnaserror-:warning01,Warning03,bc42024,58000,42376"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) ' TEST: Verify that specific promotions and suppressions (via /warnaserror[+/-]:) override general ones (i.e. /warnaserror[+/-]). output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:warning01,Warning03,bc42024,58000,42376", "/warnaserror-"}, expectedWarningCount:=4) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : warning Warning03: Throwing a diagnostic for types declared", output, StringComparison.Ordinal) Assert.Contains("a.vb(4) : warning BC42024: Unused local variable: 'x'.", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")> <WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")> <Fact> Public Sub NoWarnAndWarnAsError_ErrorDiagnostic() ' This assembly has an ErrorDiagnosticAnalyzer type which should produce custom error ' diagnostics for #Disable directives present in the compilations created in this test. Dim source = "Imports System #Disable Warning" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' TEST: Verify that custom error diagnostic Error01 can't be suppressed via /nowarn. Dim output = VerifyOutput(dir, file, additionalFlags:={"/nowarn"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) ' TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:Error01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:ERROR01"}, expectedWarningCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) ' TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/nowarn:ERROR01,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:ERROR01,42376", "/warnaserror"}) ' TEST: Verify that /nowarn: overrides /warnaserror+:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:Error01,42376", "/nowarn:ERROR01,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:ERROR01,42376", "/warnaserror:Error01,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-", "/nowarn:ERROR01,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:ERROR01,42376", "/warnaserror-"}) ' TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Error01,42376", "/nowarn:ERROR01,42376"}) ' TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags:={"/nowarn:ERROR01,42376", "/warnaserror-:Error01,42376"}) ' TEST: Verify that nothing bad happens when using /warnaserror[+/-] when custom error diagnostic Error01 is present. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror", "/nowarn:42376"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+", "/nowarn:42376"}, expectedErrorCount:=1) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) ' TEST: Verify that nothing bad happens if someone passes custom error diagnostic Error01 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror:Error01"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror+:ERROR01"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, additionalFlags:={"/warnaserror-:Error01"}, expectedWarningCount:=1, expectedErrorCount:=1) Assert.Contains("warning BC42376", output, StringComparison.Ordinal) Assert.Contains("a.vb(2) : error Error01: Throwing a diagnostic for #Disable", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")> <Fact> Public Sub NoWarnAndWarnAsError_CompilerErrorDiagnostic() Dim source = "Imports System Module Module1 Sub Main Dim x as Integer = New Exception() End Sub End Module" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) Dim output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) ' TEST: Verify that compiler error BC30311 can't be suppressed via /nowarn. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) ' TEST: Verify that compiler error BC30311 can't be suppressed via /nowarn:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:BC30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:bc30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) ' TEST: Verify that nothing bad happens when using /warnaserror[+/-] when compiler error BC30311 is present. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror+"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror-"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) ' TEST: Verify that nothing bad happens if someone passes BC30311 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror:30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror+:BC30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror+:bc30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror-:30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror-:BC30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror-:bc30311"}, expectedErrorCount:=1) Assert.Contains("a.vb(4) : error BC30311: Value of type 'Exception' cannot be converted to 'Integer'.", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <Fact, WorkItem(1091972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091972"), WorkItem(444, "CodePlex")> Public Sub Bug1091972() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( <text> ''' &lt;summary&gt;ABC...XYZ&lt;/summary&gt; Class C Shared Sub Main() Dim textStreamReader = New System.IO.StreamReader(GetType(C).Assembly.GetManifestResourceStream("doc.xml")) System.Console.WriteLine(textStreamReader.ReadToEnd()) End Sub End Class </text>.Value.Replace(vbLf, vbCrLf)) Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, String.Format("/nologo /doc:doc.xml /out:out.exe /resource:doc.xml {0}", src.ToString()), startFolder:=dir.ToString()) AssertOutput(<text></text>, output) Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml"))) Dim expected = <text> <![CDATA[ <?xml version="1.0"?> <doc> <assembly> <name> out </name> </assembly> <members> <member name="T:C"> <summary>ABC...XYZ</summary> </member> </members> </doc> ]]> </text> Using reader As New StreamReader(Path.Combine(dir.ToString(), "doc.xml")) Dim content = reader.ReadToEnd() AssertOutput(expected, content) End Using output = ProcessUtilities.RunAndGetOutput(Path.Combine(dir.ToString(), "out.exe"), startFolder:=dir.ToString()) AssertOutput(expected, output) CleanupAllGeneratedFiles(src.Path) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=0, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Info, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+:Test001", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Default, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralWarnAsErrorMinusResetsRules() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+", "/WarnAsError-", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Default, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Warn, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificWarnAsErrorMinusResetsRules() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+", "/WarnAsError-:Test001", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Warn, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+:Test002", "/WarnAsError-:Test002", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Default, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=2, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Warn, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) Assert.Equal(expected:=ReportDiagnostic.Default, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test002")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_LastGeneralWarnAsErrorTrumpsNoWarn() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/NoWarn", "/WarnAsError+", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralNoWarnTrumpsGeneralWarnAsErrorMinus() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/WarnAsError+", "/NoWarn", "/WarnAsError-", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Warn, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_GeneralNoWarnTurnsOffAllButErrors() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Error"" /> <Rule Id=""Test002"" Action=""Warning"" /> <Rule Id=""Test003"" Action=""Info"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/NoWarn", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=3, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test002")) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test003")) End Sub <Fact, WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")> Public Sub RuleSet_SpecificNoWarnAlwaysWins() Dim dir = Temp.CreateDirectory() Dim ruleSetSource = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> " Dim ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) Dim arguments = DefaultParse({"/ruleset:Rules.RuleSet", "/NoWarn:Test001", "/WarnAsError+", "/WarnAsError-:Test001", "A.vb"}, dir.Path) Assert.Empty(arguments.Errors) Assert.Equal(expected:=ReportDiagnostic.Error, actual:=arguments.CompilationOptions.GeneralDiagnosticOption) Assert.Equal(expected:=1, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions.Count) Assert.Equal(expected:=ReportDiagnostic.Suppress, actual:=arguments.CompilationOptions.SpecificDiagnosticOptions("Test001")) End Sub <Fact> Public Sub ReportAnalyzer() Dim args1 = DefaultParse({"/reportanalyzer", "a.vb"}, _baseDirectory) Assert.True(args1.ReportAnalyzer) Dim args2 = DefaultParse({"", "a.vb"}, _baseDirectory) Assert.False(args2.ReportAnalyzer) End Sub <Fact> Public Sub ReportAnalyzerOutput() Dim source As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, source}) Dim outWriter = New StringWriter() Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) Dim output = outWriter.ToString() Assert.Contains(New WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal) Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal) CleanupAllGeneratedFiles(source) End Sub <Fact> <WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")> Public Sub SkipAnalyzersParse() Dim ParsedArgs = DefaultParse({"a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.False(ParsedArgs.SkipAnalyzers) ParsedArgs = DefaultParse({"/skipanalyzers+", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.True(ParsedArgs.SkipAnalyzers) ParsedArgs = DefaultParse({"/skipanalyzers", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.True(ParsedArgs.SkipAnalyzers) ParsedArgs = DefaultParse({"/SKIPANALYZERS+", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.True(ParsedArgs.SkipAnalyzers) ParsedArgs = DefaultParse({"/skipanalyzers-", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.False(ParsedArgs.SkipAnalyzers) ParsedArgs = DefaultParse({"/skipanalyzers-", "/skipanalyzers+", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.True(ParsedArgs.SkipAnalyzers) ParsedArgs = DefaultParse({"/skipanalyzers", "/skipanalyzers-", "a.vb"}, _baseDirectory) ParsedArgs.Errors.Verify() Assert.False(ParsedArgs.SkipAnalyzers) End Sub <Theory, CombinatorialData> <WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")> Public Sub SkipAnalyzersSemantics(skipAnalyzers As Boolean) Dim source As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim skipAnalyzersFlag = "/skipanalyzers" + If(skipAnalyzers, "+", "-") Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {skipAnalyzersFlag, "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, source}) Dim outWriter = New StringWriter() Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) Dim output = outWriter.ToString() If skipAnalyzers Then Assert.DoesNotContain(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal) Assert.DoesNotContain(New WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal) Else Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal) Assert.Contains(New WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal) End If CleanupAllGeneratedFiles(source) End Sub <Fact> <WorkItem(1759, "https://github.com/dotnet/roslyn/issues/1759")> Public Sub AnalyzerDiagnosticThrowsInGetMessage() Dim source As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", source}, analyzer:=New AnalyzerThatThrowsInGetMessage) Dim outWriter = New StringWriter() Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) Dim output = outWriter.ToString() ' Verify that the diagnostic reported by AnalyzerThatThrowsInGetMessage is reported, though it doesn't have the message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal) ' Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal) Assert.Contains(NameOf(NotImplementedException), output, StringComparison.Ordinal) CleanupAllGeneratedFiles(source) End Sub <Fact> <WorkItem(3707, "https://github.com/dotnet/roslyn/issues/3707")> Public Sub AnalyzerExceptionDiagnosticCanBeConfigured() Dim source As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", $"/warnaserror:{AnalyzerExecutor.AnalyzerExceptionDiagnosticId}", source}, analyzer:=New AnalyzerThatThrowsInGetMessage) Dim outWriter = New StringWriter() Dim exitCode = vbc.Run(outWriter, Nothing) Assert.NotEqual(0, exitCode) Dim output = outWriter.ToString() ' Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal) Assert.Contains(NameOf(NotImplementedException), output, StringComparison.Ordinal) CleanupAllGeneratedFiles(source) End Sub <Fact> <WorkItem(4589, "https://github.com/dotnet/roslyn/issues/4589")> Public Sub AnalyzerReportsMisformattedDiagnostic() Dim source As String = Temp.CreateFile().WriteAllText(<text> Class C End Class </text>.Value).Path Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, {"/t:library", source}, analyzer:=New AnalyzerReportingMisformattedDiagnostic) Dim outWriter = New StringWriter() Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(0, exitCode) Dim output = outWriter.ToString() ' Verify that the diagnostic reported by AnalyzerReportingMisformattedDiagnostic is reported with the message format string, instead of the formatted message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal) Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.MessageFormat.ToString(CultureInfo.InvariantCulture), output, StringComparison.Ordinal) CleanupAllGeneratedFiles(source) End Sub <Fact> Public Sub AdditionalFileDiagnostics() Dim dir = Temp.CreateDirectory() Dim source = dir.CreateFile("a.vb").WriteAllText(<text> Class C End Class </text>.Value).Path Dim additionalFile = dir.CreateFile("AdditionalFile.txt").WriteAllText(<text> Additional File Line 1! Additional File Line 2! </text>.Value).Path Dim nonCompilerInputFile = dir.CreateFile("DummyFile.txt").WriteAllText(<text> Dummy File Line 1! </text>.Value).Path Dim analyzer = New AdditionalFileDiagnosticAnalyzer(nonCompilerInputFile) Dim arguments = {"/nologo", "/preferreduilang:en", "/vbruntime", "/t:library", "/additionalfile:" & additionalFile, ' Valid additional text file "/additionalfile:" & Assembly.GetExecutingAssembly.Location, ' Non-text file specified as an additional text file source} Dim vbc = New MockVisualBasicCompiler(Nothing, _baseDirectory, arguments, analyzer) Dim outWriter = New StringWriter() Dim exitCode = vbc.Run(outWriter, Nothing) Assert.Equal(1, exitCode) Dim output = outWriter.ToString() AssertOutput( String.Format(<text> AdditionalFile.txt(1) : warning AdditionalFileDiagnostic: Additional File Diagnostic: AdditionalFile Additional File Line 1! ~~~~~~~~~~ vbc : warning AdditionalFileDiagnostic: Additional File Diagnostic: {0} vbc : warning AdditionalFileDiagnostic: Additional File Diagnostic: AdditionalFile vbc : warning AdditionalFileDiagnostic: Additional File Diagnostic: DummyFile vbc : warning AdditionalFileDiagnostic: Additional File Diagnostic: NonExistentPath vbc : error BC2015: the file '{1}' is not a text file </text>.Value.ToString(), IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly.Location), Assembly.GetExecutingAssembly.Location), output, fileName:="AdditionalFile.txt") CleanupAllGeneratedFiles(source) CleanupAllGeneratedFiles(additionalFile) CleanupAllGeneratedFiles(nonCompilerInputFile) End Sub <Fact, WorkItem(1093063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1093063")> Public Sub VerifyDiagnosticSeverityNotLocalized() Dim source = <![CDATA[ Class A End Class ]]> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile(fileName) file.WriteAllText(source.Value) Dim output As New StringWriter() Dim vbc As New MockVisualBasicCompiler(Nothing, dir.Path, {"/nologo", "/target:exe", fileName}) vbc.Run(output, Nothing) ' If "error" was localized, below assert will fail on PLOC builds. The output would be something like: "!pTCvB!vbc : !FLxft!error 表! BC30420:" Assert.Contains("error BC30420:", output.ToString()) CleanupAllGeneratedFiles(file.Path) End Sub <ConditionalFact(GetType(WindowsOnly))> Public Sub SourceFile_BadPath() Dim args = DefaultParse({"e:c:\test\test.cs", "/t:library"}, _baseDirectory) args.Errors.Verify(Diagnostic(ERRID.FTL_InvalidInputFileName).WithArguments("e:c:\test\test.cs").WithLocation(1, 1)) End Sub <ConditionalFact(GetType(WindowsOnly))> Public Sub FilePaths() Dim args = FullParse("\\unc\path\a.vb b.vb c:\path\c.vb", "e:\temp") Assert.Equal( New String() {"\\unc\path\a.vb", "e:\temp\b.vb", "c:\path\c.vb"}, args.SourceFiles.Select(Function(x) x.Path)) args = FullParse("\\unc\path\a.vb ""b.vb"" c:\path\c.vb", "e:\temp") Assert.Equal( New String() {"\\unc\path\a.vb", "e:\temp\b.vb", "c:\path\c.vb"}, args.SourceFiles.Select(Function(x) x.Path)) args = FullParse("""b"".vb""", "e:\temp") Assert.Equal( New String() {"e:\temp\b.vb"}, args.SourceFiles.Select(Function(x) x.Path)) End Sub <ConditionalFact(GetType(WindowsOnly))> Public Sub ReferencePathsEx() Dim args = FullParse("/nostdlib /vbruntime- /noconfig /r:a.dll,b.dll test.vb", "e:\temp") Assert.Equal( New String() {"a.dll", "b.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) args = FullParse("/nostdlib /vbruntime- /noconfig /r:""a.dll,b.dll"" test.vb", "e:\temp") Assert.Equal( New String() {"a.dll,b.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) args = FullParse("/nostdlib /vbruntime- /noconfig /r:""lib, ex\a.dll"",b.dll test.vb", "e:\temp") Assert.Equal( New String() {"lib, ex\a.dll", "b.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) args = FullParse("/nostdlib /vbruntime- /noconfig /r:""lib, ex\a.dll"" test.vb", "e:\temp") Assert.Equal( New String() {"lib, ex\a.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) End Sub <ConditionalFact(GetType(WindowsOnly))> Public Sub ParseAssemblyReferences() Dim parseCore = Sub(value As String, paths As String()) Dim list As New List(Of Diagnostic) Dim references = VisualBasicCommandLineParser.ParseAssemblyReferences("", value, list, embedInteropTypes:=False) Assert.Equal(0, list.Count) Assert.Equal(paths, references.Select(Function(r) r.Reference)) End Sub parseCore("""a.dll""", New String() {"a.dll"}) parseCore("a,b", New String() {"a", "b"}) parseCore("""a,b""", New String() {"a,b"}) ' This is an intentional deviation from the native compiler. BCL docs on MSDN, MSBuild and the C# compiler ' treat a semicolon as a separator. VB compiler was the lone holdout here. Rather than deviate we decided ' to unify the behavior. parseCore("a;b", New String() {"a", "b"}) parseCore("""a;b""", New String() {"a;b"}) ' Note this case can only happen when it is the last option on the command line. When done ' in another position the command line splitting routine would continue parsing all the text ' after /r:"a as it resides in an unterminated quote. parseCore("""a", New String() {"a"}) parseCore("a""mid""b", New String() {"amidb"}) End Sub <Fact> Public Sub PublicSign() Dim args As VisualBasicCommandLineArguments Dim baseDir = "c:\test" Dim parse = Function(x As String) FullParse(x, baseDir) args = parse("/publicsign a.exe") Assert.True(args.CompilationOptions.PublicSign) args = parse("/publicsign+ a.exe") Assert.True(args.CompilationOptions.PublicSign) args = parse("/publicsign- a.exe") Assert.False(args.CompilationOptions.PublicSign) args = parse("a.exe") Assert.False(args.CompilationOptions.PublicSign) End Sub <WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")> <Fact> Public Sub PublicSign_KeyFileRelativePath() Dim parsedArgs = FullParse("/publicsign /keyfile:test.snk a.cs", _baseDirectory) Assert.Equal(Path.Combine(_baseDirectory, "test.snk"), parsedArgs.CompilationOptions.CryptoKeyFile) parsedArgs.Errors.Verify() End Sub <WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> <Fact> Public Sub PublicSignWithEmptyKeyPath() Dim parsedArgs = FullParse("/publicsign /keyfile: a.cs", _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keyfile", ":<file>").WithLocation(1, 1)) End Sub <WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")> <Fact> Public Sub PublicSignWithEmptyKeyPath2() Dim parsedArgs = FullParse("/publicsign /keyfile:"""" a.cs", _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ArgumentRequired).WithArguments("keyfile", ":<file>").WithLocation(1, 1)) End Sub <ConditionalFact(GetType(WindowsOnly))> Public Sub CommandLineMisc() Dim args As VisualBasicCommandLineArguments Dim baseDir = "c:\test" Dim parse = Function(x As String) FullParse(x, baseDir) args = parse("/out:""a.exe""") Assert.Equal("a.exe", args.OutputFileName) args = parse("/out:""a-b.exe""") Assert.Equal("a-b.exe", args.OutputFileName) args = parse("/out:""a,b.exe""") Assert.Equal("a,b.exe", args.OutputFileName) ' The \ here causes " to be treated as a quote, not as an escaping construct args = parse("a\""b c""\d.cs") Assert.Equal( New String() {"c:\test\a""b", "c:\test\c\d.cs"}, args.SourceFiles.Select(Function(x) x.Path)) args = parse("a\\""b c""\d.cs") Assert.Equal( New String() {"c:\test\a\b c\d.cs"}, args.SourceFiles.Select(Function(x) x.Path)) args = parse("/nostdlib /vbruntime- /r:""a.dll"",""b.dll"" c.cs") Assert.Equal( New String() {"a.dll", "b.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) args = parse("/nostdlib /vbruntime- /r:""a-s.dll"",""b-s.dll"" c.cs") Assert.Equal( New String() {"a-s.dll", "b-s.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) args = parse("/nostdlib /vbruntime- /r:""a,s.dll"",""b,s.dll"" c.cs") Assert.Equal( New String() {"a,s.dll", "b,s.dll"}, args.MetadataReferences.Select(Function(x) x.Reference)) End Sub <WorkItem(7588, "https://github.com/dotnet/roslyn/issues/7588")> <Fact()> Public Sub Version() Dim folderName = Temp.CreateDirectory().ToString() Dim argss = { "/version", "a.cs /version /preferreduilang:en", "/version /nologo", "/version /help"} For Each args In argss Dim output = ProcessUtilities.RunAndGetOutput(s_basicCompilerExecutable, args, startFolder:=folderName) Assert.Equal(s_compilerVersion, output.Trim()) Next End Sub <Fact> Public Sub RefOut() Dim dir = Temp.CreateDirectory() Dim refDir = dir.CreateDirectory("ref") Dim src = dir.CreateFile("a.vb") src.WriteAllText(" Public Class C ''' <summary>Main method</summary> Public Shared Sub Main() System.Console.Write(""Hello"") End Sub ''' <summary>Private method</summary> Private Shared Sub PrivateMethod() System.Console.Write(""Private"") End Sub End Class") Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/define:_MYTYPE=""Empty"" ", "/nologo", "/out:a.exe", "/refout:ref/a.dll", "/doc:doc.xml", "/deterministic", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(0, exitCode) Dim exe = Path.Combine(dir.Path, "a.exe") Assert.True(File.Exists(exe)) MetadataReaderUtils.VerifyPEMetadata(exe, {"TypeDefinition:<Module>", "TypeDefinition:C"}, {"MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()", "MethodDefinition:Void C.PrivateMethod()"}, {"CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "STAThreadAttribute"} ) Dim doc = Path.Combine(dir.Path, "doc.xml") Assert.True(File.Exists(doc)) Dim content = File.ReadAllText(doc) Dim expectedDoc = "<?xml version=""1.0""?> <doc> <assembly> <name> a </name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""M:C.PrivateMethod""> <summary>Private method</summary> </member> </members> </doc>" Assert.Equal(expectedDoc, content.Trim()) Dim output = ProcessUtilities.RunAndGetOutput(exe, startFolder:=dir.Path) Assert.Equal("Hello", output.Trim()) Dim refDll = Path.Combine(refDir.Path, "a.dll") Assert.True(File.Exists(refDll)) ' The types and members that are included needs further refinement. ' See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, {"TypeDefinition:<Module>", "TypeDefinition:C"}, {"MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()"}, {"CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "STAThreadAttribute", "ReferenceAssemblyAttribute"} ) ' Clean up temp files CleanupAllGeneratedFiles(dir.Path) CleanupAllGeneratedFiles(refDir.Path) End Sub <Fact> Public Sub RefOutWithError() Dim dir = Temp.CreateDirectory() dir.CreateDirectory("ref") Dim src = dir.CreateFile("a.vb") src.WriteAllText( "Class C Public Shared Sub Main() Bad() End Sub End Class") Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/define:_MYTYPE=""Empty"" ", "/nologo", "/out:a.dll", "/refout:ref/a.dll", "/deterministic", "/preferreduilang:en", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(1, exitCode) Dim vb = Path.Combine(dir.Path, "a.vb") Dim dll = Path.Combine(dir.Path, "a.dll") Assert.False(File.Exists(dll)) Dim refDll = Path.Combine(dir.Path, Path.Combine("ref", "a.dll")) Assert.False(File.Exists(refDll)) Assert.Equal( $"{vb}(3) : error BC30451: 'Bad' is not declared. It may be inaccessible due to its protection level. Bad() ~~~", outWriter.ToString().Trim()) ' Clean up temp files CleanupAllGeneratedFiles(dir.Path) End Sub <Fact> Public Sub RefOnly() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("a.vb") src.WriteAllText( "Class C ''' <summary>Main method</summary> Public Shared Sub Main() Bad() End Sub ''' <summary>Field</summary> Private Dim field As Integer ''' <summary>Field</summary> Private Structure S ''' <summary>Struct Field</summary> Private Dim field As Integer End Structure End Class") Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, {"/define:_MYTYPE=""Empty"" ", "/nologo", "/out:a.dll", "/refonly", "/debug", "/deterministic", "/doc:doc.xml", "a.vb"}) Dim exitCode = vbc.Run(outWriter) Assert.Equal(0, exitCode) Dim refDll = Path.Combine(dir.Path, "a.dll") Assert.True(File.Exists(refDll)) ' The types and members that are included needs further refinement. ' See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, {"TypeDefinition:<Module>", "TypeDefinition:C", "TypeDefinition:S"}, {"MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()"}, {"CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "STAThreadAttribute", "ReferenceAssemblyAttribute"} ) Dim pdb = Path.Combine(dir.Path, "a.pdb") Assert.False(File.Exists(pdb)) Dim doc = Path.Combine(dir.Path, "doc.xml") Assert.True(File.Exists(doc)) Dim content = File.ReadAllText(doc) Dim expectedDoc = "<?xml version=""1.0""?> <doc> <assembly> <name> a </name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""F:C.field""> <summary>Field</summary> </member> <member name=""T:C.S""> <summary>Field</summary> </member> <member name=""F:C.S.field""> <summary>Struct Field</summary> </member> </members> </doc>" Assert.Equal(expectedDoc, content.Trim()) ' Clean up temp files CleanupAllGeneratedFiles(dir.Path) End Sub <WorkItem(13681, "https://github.com/dotnet/roslyn/issues/13681")> <Theory()> <InlineData("/t:exe", "/out:goo.dll", "goo.dll", "goo.dll.exe")> 'Output with known but different extension <InlineData("/t:exe", "/out:goo.dLL", "goo.dLL", "goo.dLL.exe")> 'Output with known but different extension (different casing) <InlineData("/t:library", "/out:goo.exe", "goo.exe", "goo.exe.dll")> 'Output with known but different extension <InlineData("/t:library", "/out:goo.eXe", "goo.eXe", "goo.eXe.dll")> 'Output with known but different extension (different casing) <InlineData("/t:module", "/out:goo.dll", "goo.dll", "goo.dll.netmodule")> 'Output with known but different extension <InlineData("/t:winmdobj", "/out:goo.netmodule", "goo.netmodule", "goo.netmodule.winmdobj")> 'Output with known but different extension <InlineData("/t:exe", "/out:goo.netmodule", "goo.netmodule", "goo.netmodule.exe")> 'Output with known but different extension <InlineData("/t:library", "/out:goo.txt", "goo.txt.dll", "goo.dll")> 'Output with unknown extension (.txt) <InlineData("/t:exe", "/out:goo.md", "goo.md.exe", "goo.exe")> 'Output with unknown extension (.md) <InlineData("/t:exe", "/out:goo", "goo.exe", "goo")> 'Output without extension <InlineData("/t:library", "/out:goo", "goo.dll", "goo")> 'Output without extension <InlineData("/t:module", "/out:goo", "goo.netmodule", "goo")> 'Output without extension <InlineData("/t:winmdobj", "/out:goo", "goo.winmdobj", "goo")> 'Output without extension <InlineData("/t:exe", "/out:goo.exe", "goo.exe", "goo.exe.exe")> 'Output with correct extension (.exe) <InlineData("/t:library", "/out:goo.dll", "goo.dll", "goo.dll.dll")> 'Output with correct extension (.dll) <InlineData("/t:module", "/out:goo.netmodule", "goo.netmodule", "goo.netmodule.netmodule")> 'Output with correct extension (.netmodule) <InlineData("/t:module", "/out:goo.NetModule", "goo.NetModule", "goo.NetModule.netmodule")> 'Output with correct extension (.netmodule) (different casing) <InlineData("/t:winmdobj", "/out:goo.winmdobj", "goo.winmdobj", "goo.winmdobj.winmdobj")> 'Output with correct extension (.winmdobj) Public Sub OutputingFilesWithDifferentExtensions(targetArg As String, outArg As String, expectedFile As String, unexpectedFile As String) Dim source = <compilation> <file name="a.vb"> <![CDATA[ Module Program Sub Main(args As String()) End Sub End Module ]]> </file> </compilation> Dim fileName = "a.vb" Dim dir = Temp.CreateDirectory() Dim sourceFile = dir.CreateFile(fileName) sourceFile.WriteAllText(source.Value) Dim output As New StringWriter() Assert.Equal(0, New MockVisualBasicCompiler(Nothing, dir.Path, {fileName, targetArg, outArg}).Run(output, Nothing)) Assert.True(File.Exists(Path.Combine(dir.Path, expectedFile)), "Expected to find: " & expectedFile) Assert.False(File.Exists(Path.Combine(dir.Path, unexpectedFile)), "Didn't expect to find: " & unexpectedFile) CleanupAllGeneratedFiles(sourceFile.Path) End Sub <Fact> Public Sub IOFailure_DisposeOutputFile() Dim srcPath = MakeTrivialExe(Temp.CreateDirectory().Path) Dim exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe") Dim vbc = New MockVisualBasicCompiler(_baseDirectory, {"/nologo", "/preferreduilang:en", $"/out:{exePath}", srcPath}) vbc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc:= Function(filePath, mode, access, share) If filePath = exePath Then Return New TestStream(backingStream:=New MemoryStream(), dispose:=Sub() Throw New IOException("Fake IOException")) End If Return File.Open(filePath, mode, access, share) End Function) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Assert.Equal(1, vbc.Run(outWriter)) Assert.Equal($"vbc : error BC2012: can't open '{exePath}' for writing: Fake IOException{Environment.NewLine}", outWriter.ToString()) End Sub <Fact> Public Sub IOFailure_DisposePdbFile() Dim srcPath = MakeTrivialExe(Temp.CreateDirectory().Path) Dim exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe") Dim pdbPath = Path.ChangeExtension(exePath, "pdb") Dim vbc = New MockVisualBasicCompiler(_baseDirectory, {"/nologo", "/preferreduilang:en", "/debug", $"/out:{exePath}", srcPath}) vbc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc:= Function(filePath, mode, access, share) If filePath = pdbPath Then Return New TestStream(backingStream:=New MemoryStream(), dispose:=Sub() Throw New IOException("Fake IOException")) End If Return File.Open(filePath, mode, access, share) End Function) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Assert.Equal(1, vbc.Run(outWriter)) Assert.Equal($"vbc : error BC2012: can't open '{pdbPath}' for writing: Fake IOException{Environment.NewLine}", outWriter.ToString()) End Sub <Fact> Public Sub IOFailure_DisposeXmlFile() Dim srcPath = MakeTrivialExe(Temp.CreateDirectory().Path) Dim xmlPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.xml") Dim vbc = New MockVisualBasicCompiler(_baseDirectory, {"/nologo", "/preferreduilang:en", $"/doc:{xmlPath}", srcPath}) vbc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc:= Function(filePath, mode, access, share) If filePath = xmlPath Then Return New TestStream(backingStream:=New MemoryStream(), dispose:=Sub() Throw New IOException("Fake IOException")) End If Return File.Open(filePath, mode, access, share) End Function) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Assert.Equal(1, vbc.Run(outWriter)) Assert.Equal($"vbc : error BC2012: can't open '{xmlPath}' for writing: Fake IOException{Environment.NewLine}", outWriter.ToString()) End Sub <Theory> <InlineData("portable")> <InlineData("full")> Public Sub IOFailure_DisposeSourceLinkFile(format As String) Dim srcPath = MakeTrivialExe(Temp.CreateDirectory().Path) Dim sourceLinkPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.json") Dim vbc = New MockVisualBasicCompiler(_baseDirectory, {"/nologo", "/preferreduilang:en", "/debug:" & format, $"/sourcelink:{sourceLinkPath}", srcPath}) vbc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc:= Function(filePath, mode, access, share) If filePath = sourceLinkPath Then Return New TestStream( backingStream:=New MemoryStream(Encoding.UTF8.GetBytes(" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } ")), dispose:=Sub() Throw New IOException("Fake IOException")) End If Return File.Open(filePath, mode, access, share) End Function) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Assert.Equal(1, vbc.Run(outWriter)) Assert.Equal($"vbc : error BC2012: can't open '{sourceLinkPath}' for writing: Fake IOException{Environment.NewLine}", outWriter.ToString()) End Sub <Fact> Public Sub CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics() Dim parsedArgs = DefaultParse({"/define:1", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "1 ^^ ^^ ").WithLocation(1, 1)) End Sub <Fact> Public Sub CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics() Dim parsedArgs = DefaultParse({"/langversion:1000", "a.cs"}, _baseDirectory) parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("langversion", "1000").WithLocation(1, 1)) End Sub <WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")> <ConditionalFact(GetType(IsEnglishLocal))> Public Sub MissingCompilerAssembly() Dim dir = Temp.CreateDirectory() Dim vbcPath = dir.CopyFile(s_basicCompilerExecutable).Path dir.CopyFile(GetType(Compilation).Assembly.Location) ' Missing Microsoft.CodeAnalysis.VisualBasic.dll. Dim result = ProcessUtilities.Run(vbcPath, arguments:="/nologo /t:library unknown.vb", workingDirectory:=dir.Path) Assert.Equal(1, result.ExitCode) Assert.Equal( $"Could not load file or assembly '{GetType(VisualBasicCompilation).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()) ' Missing System.Collections.Immutable.dll. dir.CopyFile(GetType(VisualBasicCompilation).Assembly.Location) result = ProcessUtilities.Run(vbcPath, arguments:="/nologo /t:library unknown.vb", workingDirectory:=dir.Path) Assert.Equal(1, result.ExitCode) Assert.Equal( $"Could not load file or assembly '{GetType(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()) End Sub <ConditionalFact(GetType(WindowsOnly))> <WorkItem(21935, "https://github.com/dotnet/roslyn/issues/21935")> Public Sub PdbPathNotEmittedWithoutPdb() Dim dir = Temp.CreateDirectory() Dim src = MakeTrivialExe(directory:=dir.Path) Dim args = {"/nologo", src, "/out:a.exe", "/debug-"} Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim vbc = New MockVisualBasicCompiler(Nothing, dir.Path, args) Dim exitCode = vbc.Run(outWriter) Assert.Equal(0, exitCode) Dim exePath = Path.Combine(dir.Path, "a.exe") Assert.True(File.Exists(exePath)) Using peStream = File.OpenRead(exePath) Using peReader = New PEReader(peStream) Dim debugDirectory = peReader.PEHeaders.PEHeader.DebugTableDirectory Assert.Equal(0, debugDirectory.Size) Assert.Equal(0, debugDirectory.RelativeVirtualAddress) End Using End Using End Sub <Fact> Public Sub StrongNameProviderWithCustomTempPath() Dim tempDir = Temp.CreateDirectory() Dim workingDir = Temp.CreateDirectory() workingDir.CreateFile("a.vb") Dim vbc = New MockVisualBasicCompiler(Nothing, New BuildPaths("", workingDir.Path, Nothing, tempDir.Path), {"/features:UseLegacyStrongNameProvider", "/nostdlib", "a.vb"}) Dim comp = vbc.CreateCompilation(TextWriter.Null, New TouchedFileLogger(), NullErrorLogger.Instance, Nothing) Assert.False(comp.SignUsingBuilder) End Sub Private Function MakeTrivialExe(Optional directory As String = Nothing) As String Return Temp.CreateFile(directory:=directory, prefix:="", extension:=".vb").WriteAllText(" Class Program Public Shared Sub Main() End Sub End Class").Path End Function <Fact> <WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")> Public Sub InvalidPathCharacterInPathMap() Dim filePath = Temp.CreateFile().WriteAllText("").Path Dim compiler = New MockVisualBasicCompiler(Nothing, _baseDirectory, { filePath, "/debug:embedded", "/pathmap:test\\=""", "/target:library", "/preferreduilang:en" }) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = compiler.Run(outWriter) Assert.Equal(1, exitCode) Assert.Contains("vbc : error BC37253: The pathmap option was incorrectly formatted.", outWriter.ToString(), StringComparison.Ordinal) End Sub <WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/38454")> Public Sub TestSuppression_CompilerWarning() ' warning BC40008 : 'C' is obsolete Dim source = " Imports System <Obsolete> Class C End Class Class D Inherits C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' Verify that compiler warning BC40008 is reported. Dim output = VerifyOutput(dir, file, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False) Assert.Contains("warning BC40008", output, StringComparison.Ordinal) ' Verify that compiler warning BC40008 is suppressed with diagnostic suppressor ' and info diagnostic is logged with programmatic suppression information. Dim suppressor = New DiagnosticSuppressorForId("BC40008") ' Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' Dim suppressionMessage = String.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "C"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification) Dim suppressors = ImmutableArray.Create(Of DiagnosticAnalyzer)(suppressor) output = VerifyOutput(dir, file, expectedInfoCount:=1, expectedWarningCount:=0, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=suppressors) Assert.DoesNotContain("warning BC40008", output, StringComparison.Ordinal) Assert.Contains("info SP0001", output, StringComparison.Ordinal) Assert.Contains(suppressionMessage, output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/38454")> Public Sub TestSuppression_CompilerWarningAsError() ' warning BC40008 : 'C' is obsolete Dim source = " Imports System <Obsolete> Class C End Class Class D Inherits C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' Verify that compiler warning BC40008 is reported. Dim output = VerifyOutput(dir, file, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False) Assert.Contains("warning BC40008", output, StringComparison.Ordinal) ' Verify that compiler warning BC40008 is reported as error for /warnaserror. output = VerifyOutput(dir, file, expectedErrorCount:=1, additionalFlags:={"/warnaserror+"}, includeCurrentAssemblyAsAnalyzerReference:=False) Assert.Contains("error BC40008", output, StringComparison.Ordinal) ' Verify that compiler warning BC40008 is suppressed with diagnostic suppressor even with /warnaserror ' and info diagnostic is logged with programmatic suppression information. Dim suppressor = New DiagnosticSuppressorForId("BC40008") Dim suppressors = ImmutableArray.Create(Of DiagnosticAnalyzer)(suppressor) output = VerifyOutput(dir, file, expectedInfoCount:=1, expectedWarningCount:=0, expectedErrorCount:=0, additionalFlags:={"/warnaserror+"}, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=suppressors) Assert.DoesNotContain($"warning BC40008", output, StringComparison.Ordinal) Assert.DoesNotContain($"error BC40008", output, StringComparison.Ordinal) ' Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' Dim suppressionMessage = String.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "C"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification) Assert.Contains("info SP0001", output, StringComparison.Ordinal) Assert.Contains(suppressionMessage, output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")> <Fact> Public Sub TestNoSuppression_CompilerError() ' warning BC30203 : Identifier expected Dim source = " Class End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' Verify that compiler error BC30203 is reported. Dim output = VerifyOutput(dir, file, expectedErrorCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False) Assert.Contains("error BC30203", output, StringComparison.Ordinal) ' Verify that compiler error BC30203 cannot be suppressed with diagnostic suppressor. Dim analyzers = ImmutableArray.Create(Of DiagnosticAnalyzer)(New DiagnosticSuppressorForId("BC30203")) output = VerifyOutput(dir, file, expectedErrorCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzers) Assert.Contains("error BC30203", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/38454")> Public Sub TestSuppression_AnalyzerWarning() Dim source = " Class C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' Verify that analyzer warning is reported. Dim analyzer = New CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable:=True) Dim analyzers = ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer) Dim output = VerifyOutput(dir, file, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzers) Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) ' Verify that analyzer warning is suppressed with diagnostic suppressor ' and info diagnostic is logged with programmatic suppression information. Dim suppressor = New DiagnosticSuppressorForId(analyzer.Descriptor.Id) ' Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' Dim suppressionMessage = String.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, analyzer.Descriptor.MessageFormat, suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification) Dim analyzerAndSuppressor = ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer, suppressor) output = VerifyOutput(dir, file, expectedInfoCount:=1, expectedWarningCount:=0, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzerAndSuppressor) Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) Assert.Contains("info SP0001", output, StringComparison.Ordinal) Assert.Contains(suppressionMessage, output, StringComparison.Ordinal) ' Verify that analyzer warning is reported as error for /warnaserror. output = VerifyOutput(dir, file, expectedErrorCount:=1, additionalFlags:={"/warnaserror+"}, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzers) Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) ' Verify that analyzer warning is suppressed with diagnostic suppressor even with /warnaserror ' and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(dir, file, expectedInfoCount:=1, expectedWarningCount:=0, expectedErrorCount:=0, additionalFlags:={"/warnaserror+"}, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzerAndSuppressor) Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) Assert.Contains("info SP0001", output, StringComparison.Ordinal) Assert.Contains(suppressionMessage, output, StringComparison.Ordinal) ' Verify that "NotConfigurable" analyzer warning cannot be suppressed with diagnostic suppressor even with /warnaserror. analyzer = New CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable:=False) suppressor = New DiagnosticSuppressorForId(analyzer.Descriptor.Id) analyzerAndSuppressor = ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer, suppressor) output = VerifyOutput(dir, file, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzerAndSuppressor) Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")> <Fact> Public Sub TestNoSuppression_AnalyzerError() Dim source = " Class C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("a.vb") file.WriteAllText(source) ' Verify that analyzer error is reported. Dim analyzer = New CompilationAnalyzerWithSeverity(DiagnosticSeverity.Error, configurable:=True) Dim analyzers = ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer) Dim output = VerifyOutput(dir, file, expectedErrorCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzers) Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) ' Verify that analyzer error cannot be suppressed with diagnostic suppressor. Dim suppressor = New DiagnosticSuppressorForId(analyzer.Descriptor.Id) Dim analyzerAndSuppressor = ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer, suppressor) output = VerifyOutput(dir, file, expectedErrorCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, analyzers:=analyzerAndSuppressor) Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(file.Path) End Sub <Theory> <InlineData(True)> <InlineData(False)> <WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")> Public Sub CompilerWarnAsErrorDoesNotEmit(ByVal warnAsError As Boolean) ' warning BC40008 : 'C' is obsolete Dim source = " Imports System <Obsolete> Class C End Class Class D Inherits C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("temp.vb") file.WriteAllText(source) Dim docName As String = "doc.xml" Dim additionalFlags = {$"/doc:{docName}", "/debug:full"} If warnAsError Then additionalFlags = additionalFlags.Append("/warnaserror").AsArray() End If Dim expectedErrorCount = If(warnAsError, 1, 0) Dim expectedWarningCount = If(Not warnAsError, 1, 0) Dim output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags, expectedErrorCount:=expectedErrorCount, expectedWarningCount:=expectedWarningCount) Dim expectedOutput = If(warnAsError, "error BC40008", "warning BC40008") Assert.Contains(expectedOutput, output) Dim binaryPath As String = Path.Combine(dir.Path, "temp.dll") Assert.True(IO.File.Exists(binaryPath) = Not warnAsError) Dim pdbPath As String = Path.Combine(dir.Path, "temp.pdb") Assert.True(IO.File.Exists(pdbPath) = Not warnAsError) Dim docPath As String = Path.Combine(dir.Path, docName) Assert.True(IO.File.Exists(docPath) = Not warnAsError) End Sub <Theory> <InlineData(True)> <InlineData(False)> <WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")> Public Sub AnalyzerConfigSeverityEscalationToErrorDoesNotEmit(ByVal analyzerConfigSetToError As Boolean) ' warning BC40008 : 'C' is obsolete Dim source = " Imports System <Obsolete> Class C End Class Class D Inherits C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("temp.vb") file.WriteAllText(source) Dim docName As String = "doc.xml" Dim additionalFlags = {$"/doc:{docName}", "/debug:full"} If analyzerConfigSetToError Then Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(" [*.vb] dotnet_diagnostic.bc40008.severity = error") additionalFlags = additionalFlags.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray() End If Dim expectedErrorCount = If(analyzerConfigSetToError, 1, 0) Dim expectedWarningCount = If(Not analyzerConfigSetToError, 1, 0) Dim output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags, expectedErrorCount:=expectedErrorCount, expectedWarningCount:=expectedWarningCount) Dim expectedOutput = If(analyzerConfigSetToError, "error BC40008", "warning BC40008") Assert.Contains(expectedOutput, output) Dim binaryPath As String = Path.Combine(dir.Path, "temp.dll") Assert.True(IO.File.Exists(binaryPath) = Not analyzerConfigSetToError) Dim pdbPath As String = Path.Combine(dir.Path, "temp.pdb") Assert.True(IO.File.Exists(pdbPath) = Not analyzerConfigSetToError) Dim docPath As String = Path.Combine(dir.Path, docName) Assert.True(IO.File.Exists(docPath) = Not analyzerConfigSetToError) End Sub <Theory> <InlineData(True)> <InlineData(False)> <WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")> Public Sub RulesetSeverityEscalationToErrorDoesNotEmit(ByVal rulesetSetToError As Boolean) ' warning BC40008 : 'C' is obsolete Dim source = " Imports System <Obsolete> Class C End Class Class D Inherits C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("temp.vb") file.WriteAllText(source) Dim docName As String = "doc.xml" Dim additionalFlags = {$"/doc:{docName}", "/debug:full"} If rulesetSetToError Then Dim rulesetSource = <?xml version="1.0" encoding="utf-8"?> <RuleSet Name="Ruleset1" Description="Test" ToolsVersion="12.0"> <Rules AnalyzerId="Microsoft.CodeAnalysis" RuleNamespace="Microsoft.CodeAnalysis"> <Rule Id="BC40008" Action="Error"/> </Rules> </RuleSet> Dim ruleSetFile = CreateRuleSetFile(rulesetSource) additionalFlags = additionalFlags.Append("/ruleset:" + ruleSetFile.Path).ToArray() End If Dim expectedErrorCount = If(rulesetSetToError, 1, 0) Dim expectedWarningCount = If(Not rulesetSetToError, 1, 0) Dim output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags, expectedErrorCount:=expectedErrorCount, expectedWarningCount:=expectedWarningCount) Dim expectedOutput = If(rulesetSetToError, "error BC40008", "warning BC40008") Assert.Contains(expectedOutput, output) Dim binaryPath As String = Path.Combine(dir.Path, "temp.dll") Assert.True(IO.File.Exists(binaryPath) = Not rulesetSetToError) Dim pdbPath As String = Path.Combine(dir.Path, "temp.pdb") Assert.True(IO.File.Exists(pdbPath) = Not rulesetSetToError) Dim docPath As String = Path.Combine(dir.Path, docName) Assert.True(IO.File.Exists(docPath) = Not rulesetSetToError) End Sub <Theory> <InlineData(True)> <InlineData(False)> <WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")> Public Sub AnalyzerWarnAsErrorDoesNotEmit(ByVal warnAsError As Boolean) Dim source = " Class C End Class" Dim dir = Temp.CreateDirectory() Dim file = dir.CreateFile("temp.vb") file.WriteAllText(source) Dim expectedErrorCount = If(warnAsError, 2, 0) Dim expectedWarningCount = If(Not warnAsError, 2, 0) Dim analyzer As DiagnosticAnalyzer = New WarningDiagnosticAnalyzer() ' Reports 2 warnings for each named type. Dim additionalFlags = If(warnAsError, {"/warnaserror"}, Nothing) Dim output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags, expectedErrorCount:=expectedErrorCount, expectedWarningCount:=expectedWarningCount, analyzers:=ImmutableArray.Create(analyzer)) Dim expectedODiagnosticSeverity = If(warnAsError, "error", "warning") Assert.Contains($"{expectedODiagnosticSeverity} {WarningDiagnosticAnalyzer.Warning01.Id}", output) Assert.Contains($"{expectedODiagnosticSeverity} {WarningDiagnosticAnalyzer.Warning03.Id}", output) Dim binaryPath As String = Path.Combine(dir.Path, "temp.dll") Assert.True(IO.File.Exists(binaryPath) = Not warnAsError) End Sub <WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")> <CombinatorialData, Theory> Public Sub TestAnalyzerFilteringBasedOnSeverity(ByVal defaultSeverity As DiagnosticSeverity, ByVal errorlog As Boolean) ' This test verifies that analyzer execution is skipped at build time for the following: ' 1. Analyzer reporting Hidden diagnostics ' 2. Analyzer reporting Info diagnostics, when /errorlog is not specified Dim analyzerShouldBeSkipped = defaultSeverity = DiagnosticSeverity.Hidden OrElse defaultSeverity = DiagnosticSeverity.Info AndAlso Not errorlog ' We use an analyzer that throws an exception on every analyzer callback. ' So an AD0001 analyzer exception diagnostic is reported if analyzer executed, otherwise not. Dim analyzer = New NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault:=True, defaultSeverity, throwOnAllNamedTypes:=True) Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.vb").WriteAllText(" Class C End Class") Dim args = {"/nologo", "/t:library", "/preferreduilang:en", src.Path} If errorlog Then args = args.Append("/errorlog:errorlog") End If Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, args, analyzer) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Assert.Equal(0, exitCode) Dim output = outWriter.ToString() If analyzerShouldBeSkipped Then Assert.Empty(output) Else Assert.Contains("warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+NamedTypeAnalyzerWithConfigurableEnabledByDefault' threw an exception of type 'System.NotImplementedException'", output, StringComparison.Ordinal) End If End Sub <WorkItem(47017, "https://github.com/dotnet/roslyn/issues/47017")> <CombinatorialData, Theory> Public Sub TestWarnAsErrorMinusDoesNotEnableDisabledByDefaultAnalyzers(defaultSeverity As DiagnosticSeverity, isEnabledByDefault As Boolean) ' This test verifies that '/warnaserror-:DiagnosticId' does not affect if analyzers are executed or skipped. ' Setup the analyzer to always throw an exception on analyzer callbacks for cases where we expect analyzer execution to be skipped: ' 1. Disabled by default analyzer, i.e. 'isEnabledByDefault == false'. ' 2. Default severity Hidden/Info: We only execute analyzers reporting Warning/Error severity diagnostics on command line builds. Dim analyzerShouldBeSkipped = Not isEnabledByDefault OrElse defaultSeverity = DiagnosticSeverity.Hidden OrElse defaultSeverity = DiagnosticSeverity.Info Dim analyzer = New NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity, throwOnAllNamedTypes:=analyzerShouldBeSkipped) Dim diagnosticId = analyzer.Descriptor.Id Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.cs").WriteAllText(" Class C End Class") ' Verify '/warnaserror-:DiagnosticId' behavior. Dim args = {"/warnaserror+", $"/warnaserror-:{diagnosticId}", "/nologo", "/t:library", "/preferreduilang:en", src.Path} Dim cmd = New MockVisualBasicCompiler(Nothing, dir.Path, args, analyzer) Dim outWriter = New StringWriter(CultureInfo.InvariantCulture) Dim exitCode = cmd.Run(outWriter) Dim expectedExitCode = If(Not analyzerShouldBeSkipped AndAlso defaultSeverity = DiagnosticSeverity.[Error], 1, 0) Assert.Equal(expectedExitCode, exitCode) Dim output = outWriter.ToString() If analyzerShouldBeSkipped Then Assert.Empty(output) Else Dim prefix = If(defaultSeverity = DiagnosticSeverity.Warning, "warning", "error") Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", output) End If End Sub <WorkItem(49446, "https://github.com/dotnet/roslyn/issues/49446")> <Theory> <InlineData(False, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Error)> <InlineData(True, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Warning)> <InlineData(False, DiagnosticSeverity.Warning, Nothing, DiagnosticSeverity.Error)> <InlineData(True, DiagnosticSeverity.Warning, Nothing, DiagnosticSeverity.Warning)> <InlineData(False, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Error)> <InlineData(True, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Warning)> <InlineData(False, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)> <InlineData(True, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)> Public Sub TestWarnAsErrorMinusDoesNotNullifyEditorConfig(warnAsErrorMinus As Boolean, defaultSeverity As DiagnosticSeverity, severityInConfigFile As DiagnosticSeverity?, expectedEffectiveSeverity As DiagnosticSeverity) Dim analyzer = New NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault:=True, defaultSeverity, throwOnAllNamedTypes:=False) Dim diagnosticId = analyzer.Descriptor.Id Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("test.vb").WriteAllText(" Class C End Class") Dim additionalFlags = {"/warnaserror+"} If severityInConfigFile.HasValue Then Dim severityString = DiagnosticDescriptor.MapSeverityToReport(severityInConfigFile.Value).ToAnalyzerConfigString() Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($" [*.vb] dotnet_diagnostic.{diagnosticId}.severity = {severityString}") additionalFlags = additionalFlags.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray() End If If warnAsErrorMinus Then additionalFlags = additionalFlags.Append($"/warnaserror-:{diagnosticId}").ToArray() End If Dim expectedWarningCount As Integer = 0, expectedErrorCount As Integer = 0 Select Case expectedEffectiveSeverity Case DiagnosticSeverity.Warning expectedWarningCount = 1 Case DiagnosticSeverity.[Error] expectedErrorCount = 1 Case Else Throw ExceptionUtilities.UnexpectedValue(expectedEffectiveSeverity) End Select VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, expectedWarningCount:=expectedWarningCount, expectedErrorCount:=expectedErrorCount, additionalFlags:=additionalFlags, analyzers:=ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) End Sub <Fact> <WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")> Public Sub GlobalAnalyzerConfigDiagnosticOptionsCanBeOverridenByCommandLine() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("temp.vb").WriteAllText(" Class C Private Sub M() Dim a As String End Sub End Class ") Dim globalConfig = dir.CreateFile(".globalconfig").WriteAllText(" is_global = true dotnet_diagnostic.BC42024.severity = error; ") Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(" [*.vb] dotnet_diagnostic.BC42024.severity = warning; ") Dim globalOption = "/analyzerconfig:" + globalConfig.Path Dim specificOption = "/analyzerconfig:" + analyzerConfig.Path VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, expectedWarningCount:=1) VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, expectedWarningCount:=0, additionalFlags:={"/nowarn:BC42024"}) VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, expectedErrorCount:=1, additionalFlags:={globalOption}) VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:BC42024", globalOption}) VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:42024", globalOption}) VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, expectedWarningCount:=1, additionalFlags:={globalOption, specificOption}) VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, expectedWarningCount:=0, additionalFlags:={"/nowarn:BC42024", globalOption, specificOption}) End Sub <Theory, CombinatorialData> <WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")> Public Sub WarnAsErrorIsRespectedForForWarningsConfiguredInRulesetOrGlobalConfig(useGlobalConfig As Boolean) Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("temp.vb").WriteAllText(" Class C Private Sub M() Dim a As String End Sub End Class") Dim additionalFlags = {"/warnaserror+"} If useGlobalConfig Then Dim globalConfig = dir.CreateFile(".globalconfig").WriteAllText($" is_global = true dotnet_diagnostic.BC42024.severity = warning; ") additionalFlags = additionalFlags.Append("/analyzerconfig:" & globalConfig.Path).ToArray() Else Dim ruleSetSource As String = "<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""15.0""> <Rules AnalyzerId=""Compiler"" RuleNamespace=""Compiler""> <Rule Id=""BC42024"" Action=""Warning"" /> </Rules> </RuleSet> " dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource) additionalFlags = additionalFlags.Append("/ruleset:Rules.ruleset").ToArray() End If VerifyOutput(dir, src, additionalFlags:=additionalFlags, expectedErrorCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False) End Sub <Fact> <WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")> Public Sub GlobalAnalyzerConfigSpecificDiagnosticOptionsOverrideGeneralCommandLineOptions() Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("temp.vb").WriteAllText(" Class C Private Sub M() Dim a As String End Sub End Class ") Dim globalConfig = dir.CreateFile(".globalconfig").WriteAllText(" is_global = true dotnet_diagnostic.BC42024.severity = none; ") VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/warnaserror+", "/analyzerconfig:" + globalConfig.Path}) End Sub <Theory, CombinatorialData> Public Sub TestAdditionalFileAnalyzer(registerFromInitialize As Boolean) Dim srcDirectory = Temp.CreateDirectory() Dim source = " Class C End Class" Dim srcFile = srcDirectory.CreateFile("a.vb") srcFile.WriteAllText(source) Dim additionalText = "Additional Text" Dim additionalFile = srcDirectory.CreateFile("b.txt") additionalFile.WriteAllText(additionalText) Dim diagnosticSpan = New TextSpan(2, 2) Dim analyzer As DiagnosticAnalyzer = New AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan) Dim output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/additionalfile:" & additionalFile.Path}, analyzers:=ImmutableArray.Create(analyzer)) Assert.Contains("b.txt(1) : warning ID0001", output, StringComparison.Ordinal) CleanupAllGeneratedFiles(srcDirectory.Path) End Sub <Theory> <InlineData("warning", "/warnaserror", True, False)> <InlineData("error", "/warnaserror", True, False)> <InlineData(Nothing, "/warnaserror", True, False)> <InlineData("warning", "/warnaserror:BC40008", True, False)> <InlineData("error", "/warnaserror:BC40008", True, False)> <InlineData(Nothing, "/warnaserror:BC40008", True, False)> <InlineData("warning", "/nowarn:BC40008", False, False)> <InlineData("error", "/nowarn:BC40008", False, False)> <InlineData(Nothing, "/nowarn:BC40008", False, False)> <InlineData("warning", Nothing, False, True)> <InlineData("error", Nothing, True, False)> <InlineData(Nothing, Nothing, False, True)> <WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")> Public Sub TestCompilationOptionsOverrideAnalyzerConfig_CompilerWarning(analyzerConfigSeverity As String, additionalArg As String, expectError As Boolean, expectWarning As Boolean) ' warning BC40008 : 'C' is obsolete Dim src = " Imports System <Obsolete> Class C End Class Class D Inherits C End Class" TestCompilationOptionsOverrideAnalyzerConfigCore(src, diagnosticId:="BC40008", analyzerConfigSeverity, additionalArg, expectError, expectWarning) End Sub <Theory> <InlineData("warning", "/warnaserror", True, False)> <InlineData("error", "/warnaserror", True, False)> <InlineData(Nothing, "/warnaserror", True, False)> <InlineData("warning", "/warnaserror:" & CompilationAnalyzerWithSeverity.DiagnosticId, True, False)> <InlineData("error", "/warnaserror:" & CompilationAnalyzerWithSeverity.DiagnosticId, True, False)> <InlineData(Nothing, "/warnaserror:" & CompilationAnalyzerWithSeverity.DiagnosticId, True, False)> <InlineData("warning", "/nowarn:" & CompilationAnalyzerWithSeverity.DiagnosticId, False, False)> <InlineData("error", "/nowarn:" & CompilationAnalyzerWithSeverity.DiagnosticId, False, False)> <InlineData(Nothing, "/nowarn:" & CompilationAnalyzerWithSeverity.DiagnosticId, False, False)> <InlineData("warning", Nothing, False, True)> <InlineData("error", Nothing, True, False)> <InlineData(Nothing, Nothing, False, True)> <WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")> Public Sub TestCompilationOptionsOverrideAnalyzerConfig_AnalyzerWarning(analyzerConfigSeverity As String, additionalArg As String, expectError As Boolean, expectWarning As Boolean) Dim analyzer = New CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable:=True) Dim src = " Class C End Class" TestCompilationOptionsOverrideAnalyzerConfigCore(src, CompilationAnalyzerWithSeverity.DiagnosticId, analyzerConfigSeverity, additionalArg, expectError, expectWarning, analyzer) End Sub Private Sub TestCompilationOptionsOverrideAnalyzerConfigCore( source As String, diagnosticId As String, analyzerConfigSeverity As String, additionalArg As String, expectError As Boolean, expectWarning As Boolean, ParamArray analyzers As DiagnosticAnalyzer()) Assert.True(Not expectError OrElse Not expectWarning) Dim dir = Temp.CreateDirectory() Dim src = dir.CreateFile("temp.vb").WriteAllText(source) Dim additionalArgs = Array.Empty(Of String)() If analyzerConfigSeverity IsNot Nothing Then Dim analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($" [*.vb] dotnet_diagnostic.{diagnosticId}.severity = {analyzerConfigSeverity}") additionalArgs = additionalArgs.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray() End If If Not String.IsNullOrEmpty(additionalArg) Then additionalArgs = additionalArgs.Append(additionalArg) End If Dim output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalArgs, expectedErrorCount:=If(expectError, 1, 0), expectedWarningCount:=If(expectWarning, 1, 0), analyzers:=analyzers.ToImmutableArrayOrEmpty()) If expectError Then Assert.Contains($"error {diagnosticId}", output) ElseIf expectWarning Then Assert.Contains($"warning {diagnosticId}", output) Else Assert.DoesNotContain(diagnosticId, output) End If End Sub <ConditionalFact(GetType(CoreClrOnly), Reason:="Can't load a coreclr targeting generator on net framework / mono")> Public Sub TestGeneratorsCantTargetNetFramework() Dim directory = Temp.CreateDirectory() Dim src = directory.CreateFile("test.vb").WriteAllText(" Class C End Class") 'Core Dim coreGenerator = EmitGenerator(".NETCoreApp,Version=v5.0") VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/analyzer:" & coreGenerator}) 'NetStandard Dim nsGenerator = EmitGenerator(".NETStandard,Version=v2.0") VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/analyzer:" & nsGenerator}) 'NoTarget Dim ntGenerator = EmitGenerator(targetFramework:=Nothing) VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/analyzer:" & ntGenerator}) 'Framework Dim frameworkGenerator = EmitGenerator(".NETFramework,Version=v4.7.2") Dim output = VerifyOutput(directory, src, expectedWarningCount:=2, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/analyzer:" & frameworkGenerator}) Assert.Contains("CS8850", output) Assert.Contains("CS8033", output) 'Framework, suppressed output = VerifyOutput(directory, src, expectedWarningCount:=1, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:CS8850", "/analyzer:" & frameworkGenerator}) Assert.Contains("CS8033", output) VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference:=False, additionalFlags:={"/nowarn:CS8850,CS8033", "/analyzer:" & frameworkGenerator}) End Sub Private Function EmitGenerator(ByVal targetFramework As String) As String Dim targetFrameworkAttributeText As String = If(TypeOf targetFramework Is Object, $"<Assembly: System.Runtime.Versioning.TargetFramework(""{targetFramework}"")>", String.Empty) Dim generatorSource As String = $" Imports Microsoft.CodeAnalysis {targetFrameworkAttributeText} <Generator> Public Class Generator Inherits ISourceGenerator Public Sub Execute(ByVal context As GeneratorExecutionContext) End Sub Public Sub Initialize(ByVal context As GeneratorInitializationContext) End Sub End Class " Dim directory = Temp.CreateDirectory() Dim generatorPath = Path.Combine(directory.Path, "generator.dll") Dim compilation = VisualBasicCompilation.Create($"generator_{targetFramework}", {VisualBasicSyntaxTree.ParseText(generatorSource)}, TargetFrameworkUtil.GetReferences(Roslyn.Test.Utilities.TargetFramework.Standard, {MetadataReference.CreateFromAssemblyInternal(GetType(ISourceGenerator).Assembly)}), New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) compilation.VerifyDiagnostics() Dim result = compilation.Emit(generatorPath) Assert.[True](result.Success) Return generatorPath End Function End Class <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend MustInherit Class MockAbstractDiagnosticAnalyzer Inherits DiagnosticAnalyzer Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterCompilationStartAction( Sub(startContext As CompilationStartAnalysisContext) startContext.RegisterCompilationEndAction(AddressOf AnalyzeCompilation) CreateAnalyzerWithinCompilation(startContext) End Sub) End Sub Public MustOverride Sub CreateAnalyzerWithinCompilation(context As CompilationStartAnalysisContext) Public MustOverride Sub AnalyzeCompilation(context As CompilationAnalysisContext) End Class <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class HiddenDiagnosticAnalyzer Inherits MockAbstractDiagnosticAnalyzer Friend Shared ReadOnly Hidden01 As DiagnosticDescriptor = New DiagnosticDescriptor("Hidden01", "", "Throwing a diagnostic for #ExternalSource", "", DiagnosticSeverity.Hidden, isEnabledByDefault:=True) Public Overrides Sub CreateAnalyzerWithinCompilation(context As CompilationStartAnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ExternalSourceDirectiveTrivia) End Sub Public Overrides Sub AnalyzeCompilation(context As CompilationAnalysisContext) End Sub Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Hidden01) End Get End Property Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) context.ReportDiagnostic(Diagnostic.Create(Hidden01, context.Node.GetLocation())) End Sub End Class <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class InfoDiagnosticAnalyzer Inherits MockAbstractDiagnosticAnalyzer Friend Shared ReadOnly Info01 As DiagnosticDescriptor = New DiagnosticDescriptor("Info01", "", "Throwing a diagnostic for #Enable", "", DiagnosticSeverity.Info, isEnabledByDefault:=True) Friend Shared ReadOnly Info02 As DiagnosticDescriptor = New DiagnosticDescriptor("Info02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides Sub CreateAnalyzerWithinCompilation(context As CompilationStartAnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.EnableWarningDirectiveTrivia) End Sub Public Overrides Sub AnalyzeCompilation(context As CompilationAnalysisContext) End Sub Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Info01, Info02) End Get End Property Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) context.ReportDiagnostic(Diagnostic.Create(Info01, context.Node.GetLocation())) End Sub End Class <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class WarningDiagnosticAnalyzer Inherits MockAbstractDiagnosticAnalyzer Friend Shared ReadOnly Warning01 As DiagnosticDescriptor = New DiagnosticDescriptor("Warning01", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Friend Shared ReadOnly Warning02 As DiagnosticDescriptor = New DiagnosticDescriptor("Warning02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Friend Shared ReadOnly Warning03 As DiagnosticDescriptor = New DiagnosticDescriptor("Warning03", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Public Overrides Sub CreateAnalyzerWithinCompilation(context As CompilationStartAnalysisContext) context.RegisterSymbolAction(AddressOf AnalyzeSymbol, SymbolKind.NamedType) End Sub Public Overrides Sub AnalyzeCompilation(context As CompilationAnalysisContext) End Sub Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Warning01, Warning02, Warning03) End Get End Property Public Sub AnalyzeSymbol(context As SymbolAnalysisContext) context.ReportDiagnostic(Diagnostic.Create(Warning01, context.Symbol.Locations.First())) context.ReportDiagnostic(Diagnostic.Create(Warning03, context.Symbol.Locations.First())) End Sub End Class <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class ErrorDiagnosticAnalyzer Inherits MockAbstractDiagnosticAnalyzer Friend Shared ReadOnly Error01 As DiagnosticDescriptor = New DiagnosticDescriptor("Error01", "", "Throwing a diagnostic for #Disable", "", DiagnosticSeverity.Error, isEnabledByDefault:=True) Public Overrides Sub CreateAnalyzerWithinCompilation(context As CompilationStartAnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.DisableWarningDirectiveTrivia) End Sub Public Overrides Sub AnalyzeCompilation(context As CompilationAnalysisContext) End Sub Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Error01) End Get End Property Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) context.ReportDiagnostic(Diagnostic.Create(Error01, context.Node.GetLocation())) End Sub End Class Friend Class AdditionalFileDiagnosticAnalyzer Inherits MockAbstractDiagnosticAnalyzer Friend Shared ReadOnly Rule As DiagnosticDescriptor = New DiagnosticDescriptor("AdditionalFileDiagnostic", "", "Additional File Diagnostic: {0}", "", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Private ReadOnly _nonCompilerInputFile As String Public Sub New(nonCompilerInputFile As String) _nonCompilerInputFile = nonCompilerInputFile End Sub Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Rule) End Get End Property Public Overrides Sub AnalyzeCompilation(context As CompilationAnalysisContext) End Sub Public Overrides Sub CreateAnalyzerWithinCompilation(context As CompilationStartAnalysisContext) context.RegisterCompilationEndAction(AddressOf CompilationEndAction) End Sub Private Sub CompilationEndAction(context As CompilationAnalysisContext) ' Diagnostic reported on additionals file, with valid span. For Each additionalFile In context.Options.AdditionalFiles ReportDiagnostic(additionalFile.Path, context) Next ' Diagnostic reported on an additional file, but with an invalid span. ReportDiagnostic(context.Options.AdditionalFiles.First().Path, context, New TextSpan(0, 1000000)) ' Overflow span ' Diagnostic reported on a file which is not an input for the compiler. ReportDiagnostic(_nonCompilerInputFile, context) ' Diagnostic reported on a non-existent file. ReportDiagnostic("NonExistentPath", context) End Sub Private Sub ReportDiagnostic(path As String, context As CompilationAnalysisContext, Optional span As TextSpan = Nothing) If span = Nothing Then span = New TextSpan(0, 11) End If Dim linePosSpan = New LinePositionSpan(New LinePosition(0, 0), New LinePosition(0, span.End)) Dim diagLocation = Location.Create(path, span, linePosSpan) Dim diag = Diagnostic.Create(Rule, diagLocation, IO.Path.GetFileNameWithoutExtension(path)) context.ReportDiagnostic(diag) End Sub End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/CSharp/Portable/BoundTree/BoundNullCoalescingAssignmentOperator.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 Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundNullCoalescingAssignmentOperator { internal bool IsNullableValueTypeAssignment { get { var leftType = LeftOperand.Type; if (leftType?.IsNullableType() != true) { return false; } var nullableUnderlying = leftType.GetNullableUnderlyingType(); return nullableUnderlying.Equals(RightOperand.Type); } } } }
// 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 Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundNullCoalescingAssignmentOperator { internal bool IsNullableValueTypeAssignment { get { var leftType = LeftOperand.Type; if (leftType?.IsNullableType() != true) { return false; } var nullableUnderlying = leftType.GetNullableUnderlyingType(); return nullableUnderlying.Equals(RightOperand.Type); } } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/VisualStudio/Core/Def/Implementation/HierarchyItemToProjectIdMap.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IHierarchyItemToProjectIdMap), ServiceLayer.Host), Shared] internal class HierarchyItemToProjectIdMap : IHierarchyItemToProjectIdMap { private readonly VisualStudioWorkspaceImpl _workspace; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public HierarchyItemToProjectIdMap(VisualStudioWorkspaceImpl workspace) => _workspace = workspace; public bool TryGetProjectId(IVsHierarchyItem hierarchyItem, string? targetFrameworkMoniker, [NotNullWhen(true)] out ProjectId? projectId) { // A project node is represented in two different hierarchies: the solution's IVsHierarchy (where it is a leaf node) // and the project's own IVsHierarchy (where it is the root node). The IVsHierarchyItem joins them together for the // purpose of creating the tree displayed in Solution Explorer. The project's hierarchy is what is passed from the // project system to the language service, so that's the one the one to query here. To do that we need to get // the "nested" hierarchy from the IVsHierarchyItem. var nestedHierarchy = hierarchyItem.HierarchyIdentity.NestedHierarchy; // First filter the projects by matching up properties on the input hierarchy against properties on each // project's hierarchy. var candidateProjects = _workspace.CurrentSolution.Projects .Where(p => { // We're about to access various properties of the IVsHierarchy associated with the project. // The properties supported and the interpretation of their values varies from one project system // to another. This code is designed with C# and VB in mind, so we need to filter out everything // else. if (p.Language != LanguageNames.CSharp && p.Language != LanguageNames.VisualBasic) { return false; } var hierarchy = _workspace.GetHierarchy(p.Id); return hierarchy == nestedHierarchy; }) .ToArray(); // If we only have one candidate then no further checks are required. if (candidateProjects.Length == 1) { projectId = candidateProjects[0].Id; return true; } // For CPS projects, we may have a string we extracted from a $TFM-prefixed capability; compare that to the string we're given // from CPS to see if this matches. if (targetFrameworkMoniker != null) { var matchingProject = candidateProjects.FirstOrDefault(p => _workspace.TryGetDependencyNodeTargetIdentifier(p.Id) == targetFrameworkMoniker); if (matchingProject != null) { projectId = matchingProject.Id; return true; } } // If we have multiple candidates then we might be dealing with Web Application Projects. In this case // there will be one main project plus one project for each open aspx/cshtml/vbhtml file, all with // identical properties on their hierarchies. We can find the main project by taking the first project // without a ContainedDocument. foreach (var candidateProject in candidateProjects) { if (!candidateProject.DocumentIds.Any(id => ContainedDocument.TryGetContainedDocument(id) != null)) { projectId = candidateProject.Id; return true; } } projectId = null; return false; } } }
// 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IHierarchyItemToProjectIdMap), ServiceLayer.Host), Shared] internal class HierarchyItemToProjectIdMap : IHierarchyItemToProjectIdMap { private readonly VisualStudioWorkspaceImpl _workspace; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public HierarchyItemToProjectIdMap(VisualStudioWorkspaceImpl workspace) => _workspace = workspace; public bool TryGetProjectId(IVsHierarchyItem hierarchyItem, string? targetFrameworkMoniker, [NotNullWhen(true)] out ProjectId? projectId) { // A project node is represented in two different hierarchies: the solution's IVsHierarchy (where it is a leaf node) // and the project's own IVsHierarchy (where it is the root node). The IVsHierarchyItem joins them together for the // purpose of creating the tree displayed in Solution Explorer. The project's hierarchy is what is passed from the // project system to the language service, so that's the one the one to query here. To do that we need to get // the "nested" hierarchy from the IVsHierarchyItem. var nestedHierarchy = hierarchyItem.HierarchyIdentity.NestedHierarchy; // First filter the projects by matching up properties on the input hierarchy against properties on each // project's hierarchy. var candidateProjects = _workspace.CurrentSolution.Projects .Where(p => { // We're about to access various properties of the IVsHierarchy associated with the project. // The properties supported and the interpretation of their values varies from one project system // to another. This code is designed with C# and VB in mind, so we need to filter out everything // else. if (p.Language != LanguageNames.CSharp && p.Language != LanguageNames.VisualBasic) { return false; } var hierarchy = _workspace.GetHierarchy(p.Id); return hierarchy == nestedHierarchy; }) .ToArray(); // If we only have one candidate then no further checks are required. if (candidateProjects.Length == 1) { projectId = candidateProjects[0].Id; return true; } // For CPS projects, we may have a string we extracted from a $TFM-prefixed capability; compare that to the string we're given // from CPS to see if this matches. if (targetFrameworkMoniker != null) { var matchingProject = candidateProjects.FirstOrDefault(p => _workspace.TryGetDependencyNodeTargetIdentifier(p.Id) == targetFrameworkMoniker); if (matchingProject != null) { projectId = matchingProject.Id; return true; } } // If we have multiple candidates then we might be dealing with Web Application Projects. In this case // there will be one main project plus one project for each open aspx/cshtml/vbhtml file, all with // identical properties on their hierarchies. We can find the main project by taking the first project // without a ContainedDocument. foreach (var candidateProject in candidateProjects) { if (!candidateProject.DocumentIds.Any(id => ContainedDocument.TryGetContainedDocument(id) != null)) { projectId = candidateProject.Id; return true; } } projectId = null; return false; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Test/Resources/Core/SymbolsTests/netModule/netModule2.netmodule
MZ@ !L!This program cannot be run in DOS mode. $PELQK " @@ `@!S@  H.text  `.reloc @@B!HX `( *BSJB v4.0.30319l#~D#Strings8#US@#GUIDP#BlobG%3.!P (  (  <Module>mscorlibClass2SystemObject.ctornetModule2.netmodule l[޸Kpz\V4 !! !_CorExeMainmscoree.dll% @ 2
MZ@ !L!This program cannot be run in DOS mode. $PELQK " @@ `@!S@  H.text  `.reloc @@B!HX `( *BSJB v4.0.30319l#~D#Strings8#US@#GUIDP#BlobG%3.!P (  (  <Module>mscorlibClass2SystemObject.ctornetModule2.netmodule l[޸Kpz\V4 !! !_CorExeMainmscoree.dll% @ 2
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Features/Core/Portable/AddParameter/IAddParameterService.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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.AddParameter { internal interface IAddParameterService { /// <summary> /// Checks if there are indications that there might be more than one declarations that need to be fixed. /// The check does not look-up if there are other declarations (this is done later in the CodeAction). /// </summary> bool HasCascadingDeclarations(IMethodSymbol method); /// <summary> /// Adds a parameter to a method. /// </summary> /// <param name="newParameterIndex"><see langword="null"/> to add as the final parameter</param> /// <returns></returns> Task<Solution> AddParameterAsync( Document invocationDocument, IMethodSymbol method, ITypeSymbol newParamaterType, RefKind refKind, string parameterName, int? newParameterIndex, bool fixAllReferences, 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. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.AddParameter { internal interface IAddParameterService { /// <summary> /// Checks if there are indications that there might be more than one declarations that need to be fixed. /// The check does not look-up if there are other declarations (this is done later in the CodeAction). /// </summary> bool HasCascadingDeclarations(IMethodSymbol method); /// <summary> /// Adds a parameter to a method. /// </summary> /// <param name="newParameterIndex"><see langword="null"/> to add as the final parameter</param> /// <returns></returns> Task<Solution> AddParameterAsync( Document invocationDocument, IMethodSymbol method, ITypeSymbol newParamaterType, RefKind refKind, string parameterName, int? newParameterIndex, bool fixAllReferences, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionFixAllTests.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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.SimplifyLinqExpression; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.SimplifyLinqExpression { using VerifyCS = CSharpCodeFixVerifier< CSharpSimplifyLinqExpressionDiagnosticAnalyzer, CSharpSimplifyLinqExpressionCodeFixProvider>; public partial class CSharpSimplifyLinqExpressionTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument() { await new VerifyCS.Test { TestCode = @" using System; using System.Linq; using System.Collections.Generic; class C { static void M() { IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" }; var test1 = [|test.Where(x => x.Equals('!')).Any()|]; var test2 = [|test.Where(x => x.Equals('!')).SingleOrDefault()|]; var test3 = [|test.Where(x => x.Equals('!')).Last()|]; var test4 = [|test.Where(x => x.Equals('!')).Count()|]; var test5 = [|test.Where(x => x.Equals('!')).FirstOrDefault()|]; } }", FixedCode = @" using System; using System.Linq; using System.Collections.Generic; class C { static void M() { IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" }; var test1 = test.Any(x => x.Equals('!')); var test2 = test.SingleOrDefault(x => x.Equals('!')); var test3 = test.Last(x => x.Equals('!')); var test4 = test.Count(x => x.Equals('!')); var test5 = test.FirstOrDefault(x => x.Equals('!')); } }", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocumentExplicitCall() { var testCode = @" using System; using System.Linq; using System.Collections.Generic; class C { static void M() { IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" }; var test1 = [|Enumerable.Where(test, x => x.Equals(""!"")).Any()|]; var test2 = [|Enumerable.Where(test, x => x.Equals(""!"")).SingleOrDefault()|]; var test3 = [|Enumerable.Where(test, x => x.Equals(""!"")).Last()|]; var test4 = [|Enumerable.Where(test, x => x.Equals(""!"")).Count()|]; var test5 = [|Enumerable.Where(test, x => x.Equals(""!"")).FirstOrDefault()|]; } }"; var fixedCode = @" using System; using System.Linq; using System.Collections.Generic; class C { static void M() { IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" }; var test1 = Enumerable.Any(test, x => x.Equals(""!"")); var test2 = Enumerable.SingleOrDefault(test, x => x.Equals(""!"")); var test3 = Enumerable.Last(test, x => x.Equals(""!"")); var test4 = Enumerable.Count(test, x => x.Equals(""!"")); var test5 = Enumerable.FirstOrDefault(test, x => x.Equals(""!"")); } }"; await VerifyCS.VerifyCodeFixAsync(testCode, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task NestedInDocument() { await new VerifyCS.Test { TestCode = @" using System; using System.Linq; using System.Collections.Generic; class C { static void M() { var test = new List<string> { ""hello"", ""world"", ""!"" }; var test1 = [|test.Where(x => x.Equals('!')).Any()|]; var test2 = [|test.Where(x => x.Equals('!')).SingleOrDefault()|]; var test3 = [|test.Where(x => x.Equals('!')).Last()|]; var test4 = test.Where(x => x.Equals('!')).Count(); var test5 = from x in test where x.Equals('!') select x; var test6 = [|test.Where(a => [|a.Where(s => s.Equals(""hello"")).FirstOrDefault()|].Equals(""hello"")).FirstOrDefault()|]; } }", FixedCode = @" using System; using System.Linq; using System.Collections.Generic; class C { static void M() { var test = new List<string> { ""hello"", ""world"", ""!"" }; var test1 = test.Any(x => x.Equals('!')); var test2 = test.SingleOrDefault(x => x.Equals('!')); var test3 = test.Last(x => x.Equals('!')); var test4 = test.Where(x => x.Equals('!')).Count(); var test5 = from x in test where x.Equals('!') select x; var test6 = test.FirstOrDefault(a => a.FirstOrDefault(s => s.Equals(""hello"")).Equals(""hello"")); } }", }.RunAsync(); } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.SimplifyLinqExpression; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.SimplifyLinqExpression { using VerifyCS = CSharpCodeFixVerifier< CSharpSimplifyLinqExpressionDiagnosticAnalyzer, CSharpSimplifyLinqExpressionCodeFixProvider>; public partial class CSharpSimplifyLinqExpressionTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument() { await new VerifyCS.Test { TestCode = @" using System; using System.Linq; using System.Collections.Generic; class C { static void M() { IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" }; var test1 = [|test.Where(x => x.Equals('!')).Any()|]; var test2 = [|test.Where(x => x.Equals('!')).SingleOrDefault()|]; var test3 = [|test.Where(x => x.Equals('!')).Last()|]; var test4 = [|test.Where(x => x.Equals('!')).Count()|]; var test5 = [|test.Where(x => x.Equals('!')).FirstOrDefault()|]; } }", FixedCode = @" using System; using System.Linq; using System.Collections.Generic; class C { static void M() { IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" }; var test1 = test.Any(x => x.Equals('!')); var test2 = test.SingleOrDefault(x => x.Equals('!')); var test3 = test.Last(x => x.Equals('!')); var test4 = test.Count(x => x.Equals('!')); var test5 = test.FirstOrDefault(x => x.Equals('!')); } }", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocumentExplicitCall() { var testCode = @" using System; using System.Linq; using System.Collections.Generic; class C { static void M() { IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" }; var test1 = [|Enumerable.Where(test, x => x.Equals(""!"")).Any()|]; var test2 = [|Enumerable.Where(test, x => x.Equals(""!"")).SingleOrDefault()|]; var test3 = [|Enumerable.Where(test, x => x.Equals(""!"")).Last()|]; var test4 = [|Enumerable.Where(test, x => x.Equals(""!"")).Count()|]; var test5 = [|Enumerable.Where(test, x => x.Equals(""!"")).FirstOrDefault()|]; } }"; var fixedCode = @" using System; using System.Linq; using System.Collections.Generic; class C { static void M() { IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" }; var test1 = Enumerable.Any(test, x => x.Equals(""!"")); var test2 = Enumerable.SingleOrDefault(test, x => x.Equals(""!"")); var test3 = Enumerable.Last(test, x => x.Equals(""!"")); var test4 = Enumerable.Count(test, x => x.Equals(""!"")); var test5 = Enumerable.FirstOrDefault(test, x => x.Equals(""!"")); } }"; await VerifyCS.VerifyCodeFixAsync(testCode, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task NestedInDocument() { await new VerifyCS.Test { TestCode = @" using System; using System.Linq; using System.Collections.Generic; class C { static void M() { var test = new List<string> { ""hello"", ""world"", ""!"" }; var test1 = [|test.Where(x => x.Equals('!')).Any()|]; var test2 = [|test.Where(x => x.Equals('!')).SingleOrDefault()|]; var test3 = [|test.Where(x => x.Equals('!')).Last()|]; var test4 = test.Where(x => x.Equals('!')).Count(); var test5 = from x in test where x.Equals('!') select x; var test6 = [|test.Where(a => [|a.Where(s => s.Equals(""hello"")).FirstOrDefault()|].Equals(""hello"")).FirstOrDefault()|]; } }", FixedCode = @" using System; using System.Linq; using System.Collections.Generic; class C { static void M() { var test = new List<string> { ""hello"", ""world"", ""!"" }; var test1 = test.Any(x => x.Equals('!')); var test2 = test.SingleOrDefault(x => x.Equals('!')); var test3 = test.Last(x => x.Equals('!')); var test4 = test.Where(x => x.Equals('!')).Count(); var test5 = from x in test where x.Equals('!') select x; var test6 = test.FirstOrDefault(a => a.FirstOrDefault(s => s.Equals(""hello"")).Equals(""hello"")); } }", }.RunAsync(); } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Core/CodeAnalysisTest/CachingLookupTests.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.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { /// <summary> /// Tests for CachingLookup. /// </summary> public class CachingLookupTests { private readonly Random _randomCaseGenerator = new Random(17); private int[] RandomNumbers(int length, int seed) { Random rand = new Random(seed); int[] result = new int[length]; for (int i = 0; i < length; ++i) { result[i] = rand.Next(100, ((length / 10) + 4) * 100); } return result; } private HashSet<string> Keys(int[] numbers, bool randomCase, IEqualityComparer<string> comparer) { var keys = new HashSet<string>(comparer); foreach (var n in numbers) { keys.Add(GetKey(n, randomCase)); } return keys; } private string GetKey(int number, bool randomCase) { if (randomCase) { bool upper = _randomCaseGenerator.Next(2) == 0; return (upper ? "AA" : "aa") + Right2Chars(number.ToString()); } else { return "AA" + Right2Chars(number.ToString()); } } private ImmutableArray<int> Values(string key, int[] numbers, bool ignoreCase) { return (from n in numbers where string.Equals(GetKey(n, ignoreCase), key, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) select n).ToArray().AsImmutableOrNull(); } private ILookup<string, int> CreateLookup(int[] numbers, bool randomCase) { if (randomCase) { return numbers.ToLookup(n => GetKey(n, randomCase), StringComparer.OrdinalIgnoreCase); } else { return numbers.ToLookup(n => GetKey(n, randomCase), StringComparer.Ordinal); } } private string Right2Chars(string s) { return s.Substring(s.Length - 2); } private void CheckEqualEnumerable<T>(IEnumerable<T> e1, IEnumerable<T> e2) { List<T> l1 = e1.ToList(); List<T> l2 = e2.ToList(); Assert.Equal(l1.Count, l2.Count); foreach (T item in l1) { Assert.Contains(item, l2); } foreach (T item in l2) { Assert.Contains(item, l1); } } private void CompareLookups1(ILookup<string, int> look1, CachingDictionary<string, int> look2, HashSet<string> keys) { foreach (string k in keys) { Assert.Equal(look1.Contains(k), look2.Contains(k)); CheckEqualEnumerable(look1[k], look2[k]); } foreach (string k in new string[] { "goo", "bar", "banana", "flibber" }) { Assert.False(look1.Contains(k)); Assert.False(look2.Contains(k)); Assert.Empty(look1[k]); Assert.Empty(look2[k]); } } private void CompareLookups2(ILookup<string, int> look1, CachingDictionary<string, int> look2, HashSet<string> keys) { foreach (string k in look1.Select(g => g.Key)) { CheckEqualEnumerable(look1[k], look2[k]); } foreach (string k in look2.Keys) { CheckEqualEnumerable(look1[k], look2[k]); } Assert.Equal(look1.Count, look2.Count); } private void CompareLookups2(CachingDictionary<string, int> look1, ILookup<string, int> look2, HashSet<string> keys) { foreach (string k in look1.Keys) { CheckEqualEnumerable(look1[k], look2[k]); } foreach (string k in look2.Select(g => g.Key)) { CheckEqualEnumerable(look1[k], look2[k]); } Assert.Equal(look1.Count, look2.Count); } [Fact] public void CachingLookupCorrectResults() { StringComparer comparer = StringComparer.Ordinal; int[] numbers = RandomNumbers(200, 11234); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } var look1 = CreateLookup(numbers, false); var look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, false, comparer: c), comparer); CompareLookups1(look1, look2, Keys(numbers, false, comparer)); look1 = CreateLookup(numbers, false); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, false, comparer: c), comparer); CompareLookups2(look1, look2, Keys(numbers, false, comparer)); CompareLookups1(look1, look2, Keys(numbers, false, comparer)); look1 = CreateLookup(numbers, false); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, false, comparer: c), comparer); CompareLookups2(look2, look1, Keys(numbers, false, comparer)); CompareLookups1(look1, look2, Keys(numbers, false, comparer)); } [Fact] public void CachingLookupCaseInsensitive() { StringComparer comparer = StringComparer.OrdinalIgnoreCase; int[] numbers = RandomNumbers(300, 719); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } var look1 = CreateLookup(numbers, true); var look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look1, look2, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look2, look1, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); } [Fact] public void CachingLookupCaseInsensitiveNoCacheMissingKeys() { StringComparer comparer = StringComparer.OrdinalIgnoreCase; int[] numbers = RandomNumbers(435, 19874); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } var look1 = CreateLookup(numbers, true); var look2 = new CachingDictionary<string, int>(s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>(s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look1, look2, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>(s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look2, look1, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); } // Ensure that we are called back exactly once per key. [Fact] public void CallExactlyOncePerKey() { StringComparer comparer = StringComparer.OrdinalIgnoreCase; int[] numbers = RandomNumbers(435, 19874); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } HashSet<string> lookedUp = new HashSet<string>(comparer); bool askedForKeys = false; var look1 = new CachingDictionary<string, int>(s => { Assert.False(lookedUp.Contains(s)); lookedUp.Add(s); return dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(); }, (c) => { Assert.False(askedForKeys); askedForKeys = true; return Keys(numbers, true, comparer: c); }, comparer); string key1 = GetKey(numbers[0], false); string key2 = GetKey(numbers[1], false); string key3 = GetKey(numbers[2], false); ImmutableArray<int> retval; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; } } }
// 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.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { /// <summary> /// Tests for CachingLookup. /// </summary> public class CachingLookupTests { private readonly Random _randomCaseGenerator = new Random(17); private int[] RandomNumbers(int length, int seed) { Random rand = new Random(seed); int[] result = new int[length]; for (int i = 0; i < length; ++i) { result[i] = rand.Next(100, ((length / 10) + 4) * 100); } return result; } private HashSet<string> Keys(int[] numbers, bool randomCase, IEqualityComparer<string> comparer) { var keys = new HashSet<string>(comparer); foreach (var n in numbers) { keys.Add(GetKey(n, randomCase)); } return keys; } private string GetKey(int number, bool randomCase) { if (randomCase) { bool upper = _randomCaseGenerator.Next(2) == 0; return (upper ? "AA" : "aa") + Right2Chars(number.ToString()); } else { return "AA" + Right2Chars(number.ToString()); } } private ImmutableArray<int> Values(string key, int[] numbers, bool ignoreCase) { return (from n in numbers where string.Equals(GetKey(n, ignoreCase), key, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) select n).ToArray().AsImmutableOrNull(); } private ILookup<string, int> CreateLookup(int[] numbers, bool randomCase) { if (randomCase) { return numbers.ToLookup(n => GetKey(n, randomCase), StringComparer.OrdinalIgnoreCase); } else { return numbers.ToLookup(n => GetKey(n, randomCase), StringComparer.Ordinal); } } private string Right2Chars(string s) { return s.Substring(s.Length - 2); } private void CheckEqualEnumerable<T>(IEnumerable<T> e1, IEnumerable<T> e2) { List<T> l1 = e1.ToList(); List<T> l2 = e2.ToList(); Assert.Equal(l1.Count, l2.Count); foreach (T item in l1) { Assert.Contains(item, l2); } foreach (T item in l2) { Assert.Contains(item, l1); } } private void CompareLookups1(ILookup<string, int> look1, CachingDictionary<string, int> look2, HashSet<string> keys) { foreach (string k in keys) { Assert.Equal(look1.Contains(k), look2.Contains(k)); CheckEqualEnumerable(look1[k], look2[k]); } foreach (string k in new string[] { "goo", "bar", "banana", "flibber" }) { Assert.False(look1.Contains(k)); Assert.False(look2.Contains(k)); Assert.Empty(look1[k]); Assert.Empty(look2[k]); } } private void CompareLookups2(ILookup<string, int> look1, CachingDictionary<string, int> look2, HashSet<string> keys) { foreach (string k in look1.Select(g => g.Key)) { CheckEqualEnumerable(look1[k], look2[k]); } foreach (string k in look2.Keys) { CheckEqualEnumerable(look1[k], look2[k]); } Assert.Equal(look1.Count, look2.Count); } private void CompareLookups2(CachingDictionary<string, int> look1, ILookup<string, int> look2, HashSet<string> keys) { foreach (string k in look1.Keys) { CheckEqualEnumerable(look1[k], look2[k]); } foreach (string k in look2.Select(g => g.Key)) { CheckEqualEnumerable(look1[k], look2[k]); } Assert.Equal(look1.Count, look2.Count); } [Fact] public void CachingLookupCorrectResults() { StringComparer comparer = StringComparer.Ordinal; int[] numbers = RandomNumbers(200, 11234); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } var look1 = CreateLookup(numbers, false); var look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, false, comparer: c), comparer); CompareLookups1(look1, look2, Keys(numbers, false, comparer)); look1 = CreateLookup(numbers, false); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, false, comparer: c), comparer); CompareLookups2(look1, look2, Keys(numbers, false, comparer)); CompareLookups1(look1, look2, Keys(numbers, false, comparer)); look1 = CreateLookup(numbers, false); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, false, comparer: c), comparer); CompareLookups2(look2, look1, Keys(numbers, false, comparer)); CompareLookups1(look1, look2, Keys(numbers, false, comparer)); } [Fact] public void CachingLookupCaseInsensitive() { StringComparer comparer = StringComparer.OrdinalIgnoreCase; int[] numbers = RandomNumbers(300, 719); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } var look1 = CreateLookup(numbers, true); var look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look1, look2, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>( s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look2, look1, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); } [Fact] public void CachingLookupCaseInsensitiveNoCacheMissingKeys() { StringComparer comparer = StringComparer.OrdinalIgnoreCase; int[] numbers = RandomNumbers(435, 19874); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } var look1 = CreateLookup(numbers, true); var look2 = new CachingDictionary<string, int>(s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>(s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look1, look2, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); look1 = CreateLookup(numbers, true); look2 = new CachingDictionary<string, int>(s => dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(), (c) => Keys(numbers, true, comparer: c), comparer); CompareLookups2(look2, look1, Keys(numbers, true, comparer)); CompareLookups1(look1, look2, Keys(numbers, true, comparer)); } // Ensure that we are called back exactly once per key. [Fact] public void CallExactlyOncePerKey() { StringComparer comparer = StringComparer.OrdinalIgnoreCase; int[] numbers = RandomNumbers(435, 19874); var dict = new Dictionary<string, ImmutableArray<int>>(comparer); foreach (string k in Keys(numbers, false, comparer)) { dict.Add(k, Values(k, numbers, false)); } HashSet<string> lookedUp = new HashSet<string>(comparer); bool askedForKeys = false; var look1 = new CachingDictionary<string, int>(s => { Assert.False(lookedUp.Contains(s)); lookedUp.Add(s); return dict.ContainsKey(s) ? dict[s] : ImmutableArray.Create<int>(); }, (c) => { Assert.False(askedForKeys); askedForKeys = true; return Keys(numbers, true, comparer: c); }, comparer); string key1 = GetKey(numbers[0], false); string key2 = GetKey(numbers[1], false); string key3 = GetKey(numbers[2], false); ImmutableArray<int> retval; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; retval = look1[key1]; retval = look1[key2]; retval = look1[key3]; } } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/CSharp/Portable/Syntax/DoStatementSyntax.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 Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class DoStatementSyntax { public DoStatementSyntax Update(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) => Update(AttributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static DoStatementSyntax DoStatement(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) => DoStatement(attributeLists: default, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); } }
// 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 Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class DoStatementSyntax { public DoStatementSyntax Update(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) => Update(AttributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static DoStatementSyntax DoStatement(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) => DoStatement(attributeLists: default, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); } }
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/VisualBasic/Portable/Parser/BlockContexts/StatementBlockContext.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 Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the BlockContext '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class StatementBlockContext Inherits ExecutableStatementContext Friend Sub New(kind As SyntaxKind, statement As StatementSyntax, prevContext As BlockContext) MyBase.New(kind, statement, prevContext) End Sub Friend Overrides Function CreateBlockSyntax(statement As StatementSyntax) As VisualBasicSyntaxNode Dim endStmt As EndBlockStatementSyntax = DirectCast(statement, EndBlockStatementSyntax) Dim result As VisualBasicSyntaxNode Select Case BlockKind Case SyntaxKind.WhileBlock Dim beginStmt As WhileStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.WhileBlock(beginStmt, Body(), endStmt) Case SyntaxKind.WithBlock Dim beginStmt As WithStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.WithBlock(beginStmt, Body(), endStmt) Case SyntaxKind.SyncLockBlock Dim beginStmt As SyncLockStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.SyncLockBlock(beginStmt, Body(), endStmt) Case SyntaxKind.UsingBlock Dim beginStmt As UsingStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.UsingBlock(beginStmt, Body(), endStmt) Case Else Throw ExceptionUtilities.UnexpectedValue(BlockKind) End Select FreeStatements() Return result 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 Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the BlockContext '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class StatementBlockContext Inherits ExecutableStatementContext Friend Sub New(kind As SyntaxKind, statement As StatementSyntax, prevContext As BlockContext) MyBase.New(kind, statement, prevContext) End Sub Friend Overrides Function CreateBlockSyntax(statement As StatementSyntax) As VisualBasicSyntaxNode Dim endStmt As EndBlockStatementSyntax = DirectCast(statement, EndBlockStatementSyntax) Dim result As VisualBasicSyntaxNode Select Case BlockKind Case SyntaxKind.WhileBlock Dim beginStmt As WhileStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.WhileBlock(beginStmt, Body(), endStmt) Case SyntaxKind.WithBlock Dim beginStmt As WithStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.WithBlock(beginStmt, Body(), endStmt) Case SyntaxKind.SyncLockBlock Dim beginStmt As SyncLockStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.SyncLockBlock(beginStmt, Body(), endStmt) Case SyntaxKind.UsingBlock Dim beginStmt As UsingStatementSyntax = Nothing GetBeginEndStatements(beginStmt, endStmt) result = SyntaxFactory.UsingBlock(beginStmt, Body(), endStmt) Case Else Throw ExceptionUtilities.UnexpectedValue(BlockKind) End Select FreeStatements() Return result End Function End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/VisualStudio/Core/Test/CodeModel/VisualBasic/ExternalCodePropertyTests.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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class ExternalCodePropertyTests Inherits AbstractCodePropertyTests #Region "OverrideKind tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_None() Dim code = <Code> Class C Public Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Abstract() Dim code = <Code> MustInherit Class C Public MustOverride Property $$P As Integer End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Virtual() Dim code = <Code> Class C Public Overridable Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Override() Dim code = <Code> MustInherit Class A Public MustOverride Property P As Integer End Class Class C Inherits A Public Overrides Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Sealed() Dim code = <Code> MustInherit Class A Public MustOverride Property P As Integer End Class Class C Inherits A Public NotOverridable Overrides Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) End Sub #End Region #Region "Parameter name tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParameterName() Dim code = <Code> Class C Property $$P(x As Integer, y as String) As Integer Get Return x * y End Get Set(value As Integer) End Set End Property End Class </Code> TestAllParameterNames(code, "x", "y") End Sub #End Region #Region "ReadWrite tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_GetSet() Dim code = <Code> Class C Public Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_Get() Dim code = <Code> Class C Public ReadOnly Property $$P As Integer Get End Get End Property End Class </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadOnly) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_Set() Dim code = <Code> Class C Public WriteOnly Property $$P As Integer Set(value As Integer) End Set End Property End Class </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindWriteOnly) End Sub #End Region Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True 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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class ExternalCodePropertyTests Inherits AbstractCodePropertyTests #Region "OverrideKind tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_None() Dim code = <Code> Class C Public Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Abstract() Dim code = <Code> MustInherit Class C Public MustOverride Property $$P As Integer End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Virtual() Dim code = <Code> Class C Public Overridable Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Override() Dim code = <Code> MustInherit Class A Public MustOverride Property P As Integer End Class Class C Inherits A Public Overrides Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Sealed() Dim code = <Code> MustInherit Class A Public MustOverride Property P As Integer End Class Class C Inherits A Public NotOverridable Overrides Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) End Sub #End Region #Region "Parameter name tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParameterName() Dim code = <Code> Class C Property $$P(x As Integer, y as String) As Integer Get Return x * y End Get Set(value As Integer) End Set End Property End Class </Code> TestAllParameterNames(code, "x", "y") End Sub #End Region #Region "ReadWrite tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_GetSet() Dim code = <Code> Class C Public Property $$P As Integer Get End Get Set(value As Integer) End Set End Property End Class </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_Get() Dim code = <Code> Class C Public ReadOnly Property $$P As Integer Get End Get End Property End Class </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadOnly) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_Set() Dim code = <Code> Class C Public WriteOnly Property $$P As Integer Set(value As Integer) End Set End Property End Class </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindWriteOnly) End Sub #End Region Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True End Class End Namespace
-1
dotnet/roslyn
55,099
EnC: Include added types in changed types of emit result
The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
tmat
2021-07-23T23:32:01Z
2021-07-26T21:02:38Z
5e956729df67fdd6610253b05e1a232fe595af73
ac374afe09c3d75acb41a3ae5d78d88ed1250cb6
EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones. \+ Simplify some EnC tests.
./src/Compilers/Test/Resources/Core/SymbolsTests/CustomModifiers/Modifiers.netmodule
MZ@ !L!This program cannot be run in DOS mode. $PELN! 6 @@ `@l6O@  H.text  `.reloc @@B6HX$6rp( *6rp( *6r p( *6rp( *6rp( *6rp( *r%p*6r+p( *:r1p( *0r7p( *6r?p( *( *0rOp( *( *( *6rUp( *(*0 { +*"}*( *0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*( * * *( * * *(/* * *(2* * *(5*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*( *z *z *z *z *( *****( *( *( *rapo o o o o o ( *( *BSJB v4.0.30319l #~\ p#Strings#USd#GUIDt#BlobW %3[C 8@ R ^y     -(00B43\86v9JSXY Z]GBJPVP b^ il #rz &} ) , / 2 5 8 < X<< < ? D !X !X &!? 4!X <!a S!n \!Xd!t!!!!!,!7!B!K!X"c"n$"w4"D"T"d"t"" "X!"!"""X#"#"$"X%"%"&"X'"'"("X)")"*"+#,#-$#,.4#7/D#B0T#K1d#X2t#c3#n4#w5#)6#47#?8#X9# J9# Y9# h:# w:# ;# ;#  <# <#X=#=$ >$,?$8@$XA$XA$XA$ZAM$XDBB{BBBBBBBB{{{{{{{{BH XX)X >ACHGA#X##Xc#X#X#XOW_g t}#t.}9DSSTTUUVV  J K M L ONQP %.7O(**<Module>SystemObjectSystem.Runtime.CompilerServicesIsConstConsoleWriteLineInt32.ctorCompilerGeneratedAttributeAction`1TypeGetTypeSystem.ReflectionMemberInfoget_NameModifiers.netmodulemscorlibModifiersBaseI1I2I3C3`1TC4C5PropertiesComparisonsCustomModifierOverridingACustomModifierOverridingBCustomModifierOverridingCCustomModifierOverridingDMethodCustomModifierCombinationsPropertyCustomModifierCombinationsEventCustomModifierCombinationsFieldCustomModifierCombinationsOuter`1TOuterInner`1TInnerF0F1pF2F3F4F5F6F7F8F9F10M1M3xM4<Property>k__BackingFieldget_Propertyset_PropertyvalueMethodaMethod1Method2Method1111Method1110Method1101Method1100Method1011Method1010Method1001Method1000Method0111Method0110Method0101Method0100Method0011Method0010Method0001Method0000get_Property11set_Property11get_Property10set_Property10get_Property01set_Property01get_Property00set_Property00accessor11accessor10accessor01accessor00field11field10field01field00TMethodyzPropertyProperty11Property10Property01Property00Event11Event10Event01Event00F1F2F3F4F5F6F7F8F9F10Base.M1M4 C5.M35Outer.Inner({0}, {1}, {2})lǹZwJ}Iőm        z\V4                                                                                                                   0      (  ( ( (66 6_CorDllMainmscoree.dll% @0 6
MZ@ !L!This program cannot be run in DOS mode. $PELN! 6 @@ `@l6O@  H.text  `.reloc @@B6HX$6rp( *6rp( *6r p( *6rp( *6rp( *6rp( *r%p*6r+p( *:r1p( *0r7p( *6r?p( *( *0rOp( *( *( *6rUp( *(*0 { +*"}*( *0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*( * * *( * * *(/* * *(2* * *(5*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*( *z *z *z *z *( *****( *( *( *rapo o o o o o ( *( *BSJB v4.0.30319l #~\ p#Strings#USd#GUIDt#BlobW %3[C 8@ R ^y     -(00B43\86v9JSXY Z]GBJPVP b^ il #rz &} ) , / 2 5 8 < X<< < ? D !X !X &!? 4!X <!a S!n \!Xd!t!!!!!,!7!B!K!X"c"n$"w4"D"T"d"t"" "X!"!"""X#"#"$"X%"%"&"X'"'"("X)")"*"+#,#-$#,.4#7/D#B0T#K1d#X2t#c3#n4#w5#)6#47#?8#X9# J9# Y9# h:# w:# ;# ;#  <# <#X=#=$ >$,?$8@$XA$XA$XA$ZAM$XDBB{BBBBBBBB{{{{{{{{BH XX)X >ACHGA#X##Xc#X#X#XOW_g t}#t.}9DSSTTUUVV  J K M L ONQP %.7O(**<Module>SystemObjectSystem.Runtime.CompilerServicesIsConstConsoleWriteLineInt32.ctorCompilerGeneratedAttributeAction`1TypeGetTypeSystem.ReflectionMemberInfoget_NameModifiers.netmodulemscorlibModifiersBaseI1I2I3C3`1TC4C5PropertiesComparisonsCustomModifierOverridingACustomModifierOverridingBCustomModifierOverridingCCustomModifierOverridingDMethodCustomModifierCombinationsPropertyCustomModifierCombinationsEventCustomModifierCombinationsFieldCustomModifierCombinationsOuter`1TOuterInner`1TInnerF0F1pF2F3F4F5F6F7F8F9F10M1M3xM4<Property>k__BackingFieldget_Propertyset_PropertyvalueMethodaMethod1Method2Method1111Method1110Method1101Method1100Method1011Method1010Method1001Method1000Method0111Method0110Method0101Method0100Method0011Method0010Method0001Method0000get_Property11set_Property11get_Property10set_Property10get_Property01set_Property01get_Property00set_Property00accessor11accessor10accessor01accessor00field11field10field01field00TMethodyzPropertyProperty11Property10Property01Property00Event11Event10Event01Event00F1F2F3F4F5F6F7F8F9F10Base.M1M4 C5.M35Outer.Inner({0}, {1}, {2})lǹZwJ}Iőm        z\V4                                                                                                                   0      (  ( ( (66 6_CorDllMainmscoree.dll% @0 6
-1
dotnet/roslyn
55,098
Use directory-scoped ALCs to load analyzers in .NET Core
Resolves #52177
RikkiGibson
2021-07-23T23:26:39Z
2021-08-23T19:01:28Z
e079a36f3ade7cda2a464e4fdcde0a11577fd1ea
99f45b7c174d1a2e9b6a1d810b4069600c80421d
Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177
./src/Compilers/CSharp/Test/CommandLine/CommandLineTests.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.ComponentModel; using System.Globalization; using System.IO; using System.IO.MemoryMappedFiles; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.DiaSymReader; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Roslyn.Test.Utilities.SharedResourceHelpers; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public class CommandLineTests : CommandLineTestBase { #if NETCOREAPP private static readonly string s_CSharpCompilerExecutable; private static readonly string s_DotnetCscRun; #else private static readonly string s_CSharpCompilerExecutable = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.exe")); private static readonly string s_DotnetCscRun = ExecutionConditionUtil.IsMono ? "mono" : string.Empty; #endif private static readonly string s_CSharpScriptExecutable; private static readonly string s_compilerVersion = CommonCompiler.GetProductVersion(typeof(CommandLineTests)); static CommandLineTests() { #if NETCOREAPP var cscDllPath = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.dll")); var dotnetExe = DotNetCoreSdk.ExePath; var netStandardDllPath = AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(assembly => !assembly.IsDynamic && assembly.Location.EndsWith("netstandard.dll")).Location; var netStandardDllDir = Path.GetDirectoryName(netStandardDllPath); // Since we are using references based on the UnitTest's runtime, we need to use // its runtime config when executing out program. var runtimeConfigPath = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "runtimeconfig.json"); s_CSharpCompilerExecutable = $@"""{dotnetExe}"" ""{cscDllPath}"" /r:""{netStandardDllPath}"" /r:""{netStandardDllDir}/System.Private.CoreLib.dll"" /r:""{netStandardDllDir}/System.Console.dll"" /r:""{netStandardDllDir}/System.Runtime.dll"""; s_DotnetCscRun = $@"""{dotnetExe}"" exec --runtimeconfig ""{runtimeConfigPath}"""; s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.dll", Path.Combine("csi", "csi.dll")); #else s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.exe", Path.Combine("csi", "csi.exe")); #endif } private class TestCommandLineParser : CSharpCommandLineParser { private readonly Dictionary<string, string> _responseFiles; private readonly Dictionary<string, string[]> _recursivePatterns; private readonly Dictionary<string, string[]> _patterns; public TestCommandLineParser( Dictionary<string, string> responseFiles = null, Dictionary<string, string[]> patterns = null, Dictionary<string, string[]> recursivePatterns = null, bool isInteractive = false) : base(isInteractive) { _responseFiles = responseFiles; _recursivePatterns = recursivePatterns; _patterns = patterns; } internal override IEnumerable<string> EnumerateFiles(string directory, string fileNamePattern, SearchOption searchOption) { var key = directory + "|" + fileNamePattern; if (searchOption == SearchOption.TopDirectoryOnly) { return _patterns[key]; } else { return _recursivePatterns[key]; } } internal override TextReader CreateTextFileReader(string fullPath) { return new StringReader(_responseFiles[fullPath]); } } private CSharpCommandLineArguments ScriptParse(IEnumerable<string> args, string baseDirectory) { return CSharpCommandLineParser.Script.Parse(args, baseDirectory, SdkDirectory); } private CSharpCommandLineArguments FullParse(string commandLine, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null) { sdkDirectory = sdkDirectory ?? SdkDirectory; var args = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: true); return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } [ConditionalFact(typeof(WindowsDesktopOnly))] [WorkItem(34101, "https://github.com/dotnet/roslyn/issues/34101")] public void SuppressedWarnAsErrorsStillEmit() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" #pragma warning disable 1591 public class P { public static void Main() {} }"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/errorlog:errorlog", $"/doc:{docName}", "/warnaserror", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); string exePath = Path.Combine(dir.Path, "temp.exe"); Assert.True(File.Exists(exePath)); var result = ProcessUtilities.Run(exePath, arguments: ""); Assert.Equal(0, result.ExitCode); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void XmlMemoryMapped() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C {}"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", $"/doc:{docName}", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var xmlPath = Path.Combine(dir.Path, docName); using (var fileStream = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var mmf = MemoryMappedFile.CreateFromFile(fileStream, "xmlMap", 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true)) { exitCode = cmd.Run(outWriter); Assert.StartsWith($"error CS0016: Could not write to output file '{xmlPath}' -- ", outWriter.ToString()); Assert.Equal(1, exitCode); } } [Fact] public void SimpleAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none dotnet_diagnostic.Warning01.severity = none my_option = my_val [*.txt] dotnet_diagnostic.cs0169.severity = none my_option2 = my_val2"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032", "/additionalfile:" + additionalFile.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var compilerTreeOptions = comp.Options.SyntaxTreeOptionsProvider; Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "cs0169", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "warning01", CancellationToken.None, out severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); var analyzerOptions = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = analyzerOptions.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option", out string val)); Assert.Equal("my_val", val); Assert.False(options.TryGetValue("my_option2", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); options = analyzerOptions.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option2", out val)); Assert.Equal("my_val2", val); Assert.False(options.TryGetValue("my_option", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); } [Fact] public void AnalyzerConfigBadSeverity() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = garbage"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal( $@"warning InvalidSeverityInAnalyzerConfig: The diagnostic 'cs0169' was given an invalid severity 'garbage' in the analyzer config file at '{analyzerConfig.Path}'. test.cs(4,9): warning CS0169: The field 'C._f' is never used ", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigsInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" [*.cs] dotnet_diagnostic.cs0169.severity = suppress"; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $"error CS8700: Multiple analyzer config files cannot be in the same directory ('{dir.Path}').", outWriter.ToString().TrimEnd()); } // This test should only run when the machine's default encoding is shift-JIS [ConditionalFact(typeof(WindowsDesktopOnly), typeof(HasShiftJisDefaultEncoding), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompileShiftJisOnShiftJis() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", src.Path }); Assert.Null(cmd.Arguments.Encoding); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RunWithShiftJisFile() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/codepage:932", src.Path }); Assert.Equal(932, cmd.Arguments.Encoding?.WindowsCodePage); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompilerBinariesAreAnyCPU() { Assert.Equal(ProcessorArchitecture.MSIL, AssemblyName.GetAssemblyName(s_CSharpCompilerExecutable).ProcessorArchitecture); } [Fact] public void ResponseFiles1() { string rsp = Temp.CreateFile().WriteAllText(@" /r:System.dll /nostdlib # this is ignored System.Console.WriteLine(""*?""); # this is error a.cs ").Path; var cmd = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { "b.cs" }); cmd.Arguments.Errors.Verify( // error CS2001: Source file 'System.Console.WriteLine(*?);' could not be found Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("System.Console.WriteLine(*?);")); AssertEx.Equal(new[] { "System.dll" }, cmd.Arguments.MetadataReferences.Select(r => r.Reference)); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "a.cs"), Path.Combine(WorkingDirectory, "b.cs") }, cmd.Arguments.SourceFiles.Select(file => file.Path)); CleanupAllGeneratedFiles(rsp); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void ResponseFiles_RelativePaths() { var parentDir = Temp.CreateDirectory(); var baseDir = parentDir.CreateDirectory("temp"); var dirX = baseDir.CreateDirectory("x"); var dirAB = baseDir.CreateDirectory("a b"); var dirSubDir = baseDir.CreateDirectory("subdir"); var dirGoo = parentDir.CreateDirectory("goo"); var dirBar = parentDir.CreateDirectory("bar"); string basePath = baseDir.Path; Func<string, string> prependBasePath = fileName => Path.Combine(basePath, fileName); var parser = new TestCommandLineParser(responseFiles: new Dictionary<string, string>() { { prependBasePath(@"a.rsp"), @" ""@subdir\b.rsp"" /r:..\v4.0.30319\System.dll /r:.\System.Data.dll a.cs @""..\c.rsp"" @\d.rsp /libpaths:..\goo;../bar;""a b"" " }, { Path.Combine(dirSubDir.Path, @"b.rsp"), @" b.cs " }, { prependBasePath(@"..\c.rsp"), @" c.cs /lib:x " }, { Path.Combine(Path.GetPathRoot(basePath), @"d.rsp"), @" # comment d.cs " } }, isInteractive: false); var args = parser.Parse(new[] { "first.cs", "second.cs", "@a.rsp", "last.cs" }, basePath, SdkDirectory); args.Errors.Verify(); Assert.False(args.IsScriptRunner); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); string[] references = args.MetadataReferences.Select(r => r.Reference).ToArray(); AssertEx.Equal(new[] { "first.cs", "second.cs", "b.cs", "a.cs", "c.cs", "d.cs", "last.cs" }.Select(prependBasePath), resolvedSourceFiles); AssertEx.Equal(new[] { typeof(object).Assembly.Location, @"..\v4.0.30319\System.dll", @".\System.Data.dll" }, references); AssertEx.Equal(new[] { RuntimeEnvironment.GetRuntimeDirectory() }.Concat(new[] { @"x", @"..\goo", @"../bar", @"a b" }.Select(prependBasePath)), args.ReferencePaths.ToArray()); Assert.Equal(basePath, args.BaseDirectory); } #nullable enable [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryNotAddedToKeyFileSearchPaths() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:web.config", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2021: File name 'web.config' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("web.config").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles_Wildcard() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:*", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2001: Source file '*' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("*").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } #nullable disable [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPath() { var parentDir = Temp.CreateDirectory(); var parser = CSharpCommandLineParser.Default.Parse(new[] { "file.cs", $"-out:{parentDir.Path}", "/noSdkPath" }, parentDir.Path, null); AssertEx.Equal(ImmutableArray<string>.Empty, parser.ReferencePaths); } [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPathReferenceSystemDll() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/nosdkpath", "/r:System.dll", "a.cs" }); var exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'System.dll' could not be found", outWriter.ToString().Trim()); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns() { var parser = new TestCommandLineParser( patterns: new Dictionary<string, string[]>() { { @"C:\temp|*.cs", new[] { "a.cs", "b.cs", "c.cs" } } }, recursivePatterns: new Dictionary<string, string[]>() { { @"C:\temp\a|*.cs", new[] { @"a\x.cs", @"a\b\b.cs", @"a\c.cs" } }, }); var args = parser.Parse(new[] { @"*.cs", @"/recurse:a\*.cs" }, @"C:\temp", SdkDirectory); args.Errors.Verify(); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { @"C:\temp\a.cs", @"C:\temp\b.cs", @"C:\temp\c.cs", @"C:\temp\a\x.cs", @"C:\temp\a\b\b.cs", @"C:\temp\a\c.cs" }, resolvedSourceFiles); } [Fact] public void ParseQuotedMainType() { // Verify the main switch are unquoted when used because of the issue with // MSBuild quoting some usages and not others. A quote character is not valid in either // these names. CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); args = DefaultParse(new[] { "/main:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); // Use of Cyrillic namespace args = DefaultParse(new[] { "/m:\"решения.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("решения.Class1", args.CompilationOptions.MainTypeName); } [Fact] [WorkItem(21508, "https://github.com/dotnet/roslyn/issues/21508")] public void ArgumentStartWithDashAndContainingSlash() { CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); args = DefaultParse(new[] { "-debug+/debug:portable" }, folder.Path); args.Errors.Verify( // error CS2007: Unrecognized option: '-debug+/debug:portable' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("-debug+/debug:portable").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); } [WorkItem(546009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546009")] [WorkItem(545991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545991")] [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns2() { var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); CreateFile(folder, "b.vb"); CreateFile(folder, "c.cpp"); var folderA = folder.CreateDirectory("A"); CreateFile(folderA, "A_a.cs"); CreateFile(folderA, "A_b.cs"); CreateFile(folderA, "A_c.vb"); var folderB = folder.CreateDirectory("B"); CreateFile(folderB, "B_a.cs"); CreateFile(folderB, "B_b.vb"); CreateFile(folderB, "B_c.cpx"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:. ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse: . ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:././.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); CSharpCommandLineArguments args; string[] resolvedSourceFiles; args = DefaultParse(new[] { @"/recurse:*.cp*", @"/recurse:a\*.c*", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { folder.Path + @"\c.cpp", folder.Path + @"\B\B_c.cpx", folder.Path + @"\a\A_a.cs", folder.Path + @"\a\A_b.cs", }, resolvedSourceFiles); args = DefaultParse(new[] { @"/recurse:.\\\\\\*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); args = DefaultParse(new[] { @"/recurse:.////*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFile_BadPath() { var args = DefaultParse(new[] { @"e:c:\test\test.cs", "/t:library" }, WorkingDirectory); Assert.Equal(3, args.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, args.Errors[0].Code); Assert.Equal((int)ErrorCode.WRN_NoSources, args.Errors[1].Code); Assert.Equal((int)ErrorCode.ERR_OutputNeedsName, args.Errors[2].Code); } private void CreateFile(TempDirectory folder, string file) { var f = folder.CreateFile(file); f.WriteAllText(""); } [Fact, WorkItem(546023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546023")] public void Win32ResourceArguments() { string[] args = new string[] { @"/win32manifest:..\here\there\everywhere\nonexistent" }; var parsedArgs = DefaultParse(args, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32manifest:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); } [Fact] public void Win32ResConflicts() { var parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32icon:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndIcon, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32manifest:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndManifest, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Icon: ", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:goo", "/noWin32Manifest", "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.True(parsedArgs.NoWin32Manifest); Assert.Null(parsedArgs.Win32Manifest); } [Fact] public void Win32ResInvalid() { var parsedArgs = DefaultParse(new[] { "/win32res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32res")); parsedArgs = DefaultParse(new[] { "/win32res+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32res+")); parsedArgs = DefaultParse(new[] { "/win32icon", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32icon")); parsedArgs = DefaultParse(new[] { "/win32icon+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32icon+")); parsedArgs = DefaultParse(new[] { "/win32manifest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32manifest")); parsedArgs = DefaultParse(new[] { "/win32manifest+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32manifest+")); } [Fact] public void Win32IconContainsGarbage() { string tmpFileName = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Path; var parsedArgs = DefaultParse(new[] { "/win32icon:" + tmpFileName, "a.cs" }, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_ErrorBuildingWin32Resources, errors.First().Code); Assert.Equal(1, errors.First().Arguments.Count()); CleanupAllGeneratedFiles(tmpFileName); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Win32ResQuotes() { string[] responseFile = new string[] { @" /win32res:d:\\""abc def""\a""b c""d\a.res", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.res", args.Win32ResourceFile); responseFile = new string[] { @" /win32icon:d:\\""abc def""\a""b c""d\a.ico", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.ico", args.Win32Icon); responseFile = new string[] { @" /win32manifest:d:\\""abc def""\a""b c""d\a.manifest", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.manifest", args.Win32Manifest); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseResources() { var diags = new List<Diagnostic>(); ResourceDescription desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\s""ome Fil""e.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"some File.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,""some Name"",public", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("some Name", desc.ResourceName); Assert.True(desc.IsPublic); // Use file name in place of missing resource name. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Quoted accessibility is fine. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,""private""", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Leading commas are not ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @",,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @", ,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // Trailing commas are ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private, ,", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName,publi", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("publi")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"D:rive\relative\path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"D:rive\relative\path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"inva\l*d?path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"inva\l*d?path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", (string)null, WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", "", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", " ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.True(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); var longE = new String('e', 1024); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("path,{0},private", longE), WorkingDirectory, diags, embedded: false); diags.Verify(); // Now checked during emit. diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal(longE, desc.ResourceName); Assert.False(desc.IsPublic); var longI = new String('i', 260); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("{0},e,private", longI), WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2021: File name 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii").WithLocation(1, 1)); } [Fact] public void ManagedResourceOptions() { CSharpCommandLineArguments parsedArgs; ResourceDescription resourceDescription; parsedArgs = DefaultParse(new[] { "/resource:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("a", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/res:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("b", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkresource:c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("c", resourceDescription.FileName); Assert.Equal("c", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkres:d", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("d", resourceDescription.FileName); Assert.Equal("d", resourceDescription.ResourceName); } [Fact] public void ManagedResourceOptions_SimpleErrors() { var parsedArgs = DefaultParse(new[] { "/resource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/resource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res")); parsedArgs = DefaultParse(new[] { "/RES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/RES+")); parsedArgs = DefaultParse(new[] { "/res-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res-:")); parsedArgs = DefaultParse(new[] { "/linkresource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkresource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkres", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres")); parsedArgs = DefaultParse(new[] { "/linkRES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkRES+")); parsedArgs = DefaultParse(new[] { "/linkres-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres-:")); } [Fact] public void Link_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/link:a", "/link:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Link: ,,, b ,,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/l:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/l:")); parsedArgs = DefaultParse(new[] { "/L", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/L")); parsedArgs = DefaultParse(new[] { "/l+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/l+")); parsedArgs = DefaultParse(new[] { "/link-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/link-:")); } [ConditionalFact(typeof(WindowsOnly))] public void Recurse_SimpleTests() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); var file2 = dir.CreateFile("b.cs"); var file3 = dir.CreateFile("c.txt"); var file4 = dir.CreateDirectory("d1").CreateFile("d.txt"); var file5 = dir.CreateDirectory("d2").CreateFile("e.cs"); file1.WriteAllText(""); file2.WriteAllText(""); file3.WriteAllText(""); file4.WriteAllText(""); file5.WriteAllText(""); var parsedArgs = DefaultParse(new[] { "/recurse:" + dir.ToString() + "\\*.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs", "{DIR}\\d2\\e.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "*.cs" }, dir.ToString()); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "/reCURSE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/reCURSE:")); parsedArgs = DefaultParse(new[] { "/RECURSE: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/RECURSE:")); parsedArgs = DefaultParse(new[] { "/recurse", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse")); parsedArgs = DefaultParse(new[] { "/recurse+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse+")); parsedArgs = DefaultParse(new[] { "/recurse-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse-:")); CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); CleanupAllGeneratedFiles(file3.Path); CleanupAllGeneratedFiles(file4.Path); CleanupAllGeneratedFiles(file5.Path); } [Fact] public void Reference_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/nostdlib", "/r:a", "/REFERENCE:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference: ,,, b ,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference:a=b,,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.MetadataReferences.Single().Properties.Aliases.Single()); Assert.Equal("b", parsedArgs.MetadataReferences.Single().Reference); parsedArgs = DefaultParse(new[] { "/r:a=b,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_OneAliasPerReference).WithArguments("b,,,c")); parsedArgs = DefaultParse(new[] { "/r:1=b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadExternIdentifier).WithArguments("1")); parsedArgs = DefaultParse(new[] { "/r:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/r:")); parsedArgs = DefaultParse(new[] { "/R", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/R")); parsedArgs = DefaultParse(new[] { "/reference+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference+")); parsedArgs = DefaultParse(new[] { "/reference-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference-:")); } [Fact] public void Target_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/target:exe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t")); parsedArgs = DefaultParse(new[] { "/target:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/target:xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/T+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+")); parsedArgs = DefaultParse(new[] { "/TARGET-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:")); } [Fact] public void Target_SimpleTestsNoSource() { var parsedArgs = DefaultParse(new[] { "/target:exe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/t' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:xyz" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/T+" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/T+' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/TARGET-:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/TARGET-:' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); } [Fact] public void ModuleManifest() { CSharpCommandLineArguments args = DefaultParse(new[] { "/win32manifest:blah", "/target:module", "a.cs" }, WorkingDirectory); args.Errors.Verify( // warning CS1927: Ignoring /win32manifest for module because it only applies to assemblies Diagnostic(ErrorCode.WRN_CantHaveManifestForModule)); // Illegal, but not clobbered. Assert.Equal("blah", args.Win32Manifest); } [Fact] public void ArgumentParsing() { var sdkDirectory = SdkDirectory; var parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b; c" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/help" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayLangVersions); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "//langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2001: Source file '//langversion:?' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("//langversion:?").WithLocation(1, 1) ); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version:something" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /langversion:6" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:-1", "c.csx", }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '-1' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("-1").WithLocation(1, 1)); Assert.False(parsedArgs.DisplayHelp); Assert.Equal(1, parsedArgs.SourceFiles.Length); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /r:s=d /r:d.dll" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "@roslyn_test_non_existing_file" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2011: Error opening response file 'D:\R0\Main\Binaries\Debug\dd' Diagnostic(ErrorCode.ERR_OpenResponseFile).WithArguments(Path.Combine(WorkingDirectory, @"roslyn_test_non_existing_file"))); Assert.False(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c /define:DEBUG" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\\" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r:d.dll", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/define:goo", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/define:goo' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/define:goo")); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\"/r d.dll\"" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r: d.dll", "a.cs" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); } [Theory] [InlineData("iso-1", LanguageVersion.CSharp1)] [InlineData("iso-2", LanguageVersion.CSharp2)] [InlineData("1", LanguageVersion.CSharp1)] [InlineData("1.0", LanguageVersion.CSharp1)] [InlineData("2", LanguageVersion.CSharp2)] [InlineData("2.0", LanguageVersion.CSharp2)] [InlineData("3", LanguageVersion.CSharp3)] [InlineData("3.0", LanguageVersion.CSharp3)] [InlineData("4", LanguageVersion.CSharp4)] [InlineData("4.0", LanguageVersion.CSharp4)] [InlineData("5", LanguageVersion.CSharp5)] [InlineData("5.0", LanguageVersion.CSharp5)] [InlineData("6", LanguageVersion.CSharp6)] [InlineData("6.0", LanguageVersion.CSharp6)] [InlineData("7", LanguageVersion.CSharp7)] [InlineData("7.0", LanguageVersion.CSharp7)] [InlineData("7.1", LanguageVersion.CSharp7_1)] [InlineData("7.2", LanguageVersion.CSharp7_2)] [InlineData("7.3", LanguageVersion.CSharp7_3)] [InlineData("8", LanguageVersion.CSharp8)] [InlineData("8.0", LanguageVersion.CSharp8)] [InlineData("9", LanguageVersion.CSharp9)] [InlineData("9.0", LanguageVersion.CSharp9)] [InlineData("preview", LanguageVersion.Preview)] public void LangVersion_CanParseCorrectVersions(string value, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); var scriptParsedArgs = ScriptParse(new[] { $"/langversion:{value}" }, WorkingDirectory); scriptParsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("6", "7", LanguageVersion.CSharp7)] [InlineData("7", "6", LanguageVersion.CSharp6)] [InlineData("7", "1", LanguageVersion.CSharp1)] [InlineData("6", "iso-1", LanguageVersion.CSharp1)] [InlineData("6", "iso-2", LanguageVersion.CSharp2)] [InlineData("6", "default", LanguageVersion.Default)] [InlineData("7", "default", LanguageVersion.Default)] [InlineData("iso-2", "6", LanguageVersion.CSharp6)] public void LangVersion_LatterVersionOverridesFormerOne(string formerValue, string latterValue, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{formerValue}", $"/langversion:{latterValue}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Fact] public void LangVersion_DefaultMapsCorrectly() { LanguageVersion defaultEffectiveVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Default, defaultEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:default", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(defaultEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_LatestMapsCorrectly() { LanguageVersion latestEffectiveVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Latest, latestEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:latest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Latest, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(latestEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_NoValueSpecified() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("iso-3")] [InlineData("iso1")] [InlineData("8.1")] [InlineData("10.1")] [InlineData("11")] [InlineData("1000")] public void LangVersion_BadVersion(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS1617: Invalid option 'XXX' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments(value).WithLocation(1, 1) ); } [Theory] [InlineData("0")] [InlineData("05")] [InlineData("07")] [InlineData("07.1")] [InlineData("08")] [InlineData("09")] public void LangVersion_LeadingZeroes(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS8303: Specified language version 'XXX' cannot have leading zeroes Diagnostic(ErrorCode.ERR_LanguageVersionCannotHaveLeadingZeroes).WithArguments(value).WithLocation(1, 1)); } [Theory] [InlineData("/langversion")] [InlineData("/langversion:")] [InlineData("/LANGversion:")] public void LangVersion_NoVersion(string option) { DefaultParse(new[] { option, "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/langversion:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/langversion:").WithLocation(1, 1)); } [Fact] public void LangVersion_LangVersions() { var args = DefaultParse(new[] { "/langversion:?" }, WorkingDirectory); args.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); Assert.True(args.DisplayLangVersions); } [Fact] public void LanguageVersionAdded_Canary() { // When a new version is added, this test will break. This list must be checked: // - update the "UpgradeProject" codefixer // - update all the tests that call this canary // - update MaxSupportedLangVersion (a relevant test should break when new version is introduced) // - email release management to add to the release notes (see old example: https://github.com/dotnet/core/pull/1454) AssertEx.SetEqual(new[] { "default", "1", "2", "3", "4", "5", "6", "7.0", "7.1", "7.2", "7.3", "8.0", "9.0", "10.0", "latest", "latestmajor", "preview" }, Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>().Select(v => v.ToDisplayString())); // For minor versions and new major versions, the format should be "x.y", such as "7.1" } [Fact] public void LanguageVersion_GetErrorCode() { var versions = Enum.GetValues(typeof(LanguageVersion)) .Cast<LanguageVersion>() .Except(new[] { LanguageVersion.Default, LanguageVersion.Latest, LanguageVersion.LatestMajor, LanguageVersion.Preview }) .Select(v => v.GetErrorCode()); var errorCodes = new[] { ErrorCode.ERR_FeatureNotAvailableInVersion1, ErrorCode.ERR_FeatureNotAvailableInVersion2, ErrorCode.ERR_FeatureNotAvailableInVersion3, ErrorCode.ERR_FeatureNotAvailableInVersion4, ErrorCode.ERR_FeatureNotAvailableInVersion5, ErrorCode.ERR_FeatureNotAvailableInVersion6, ErrorCode.ERR_FeatureNotAvailableInVersion7, ErrorCode.ERR_FeatureNotAvailableInVersion7_1, ErrorCode.ERR_FeatureNotAvailableInVersion7_2, ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ErrorCode.ERR_FeatureNotAvailableInVersion8, ErrorCode.ERR_FeatureNotAvailableInVersion9, ErrorCode.ERR_FeatureNotAvailableInVersion10, }; AssertEx.SetEqual(versions, errorCodes); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData(LanguageVersion.CSharp1, LanguageVersion.CSharp1), InlineData(LanguageVersion.CSharp2, LanguageVersion.CSharp2), InlineData(LanguageVersion.CSharp3, LanguageVersion.CSharp3), InlineData(LanguageVersion.CSharp4, LanguageVersion.CSharp4), InlineData(LanguageVersion.CSharp5, LanguageVersion.CSharp5), InlineData(LanguageVersion.CSharp6, LanguageVersion.CSharp6), InlineData(LanguageVersion.CSharp7, LanguageVersion.CSharp7), InlineData(LanguageVersion.CSharp7_1, LanguageVersion.CSharp7_1), InlineData(LanguageVersion.CSharp7_2, LanguageVersion.CSharp7_2), InlineData(LanguageVersion.CSharp7_3, LanguageVersion.CSharp7_3), InlineData(LanguageVersion.CSharp8, LanguageVersion.CSharp8), InlineData(LanguageVersion.CSharp9, LanguageVersion.CSharp9), InlineData(LanguageVersion.CSharp10, LanguageVersion.CSharp10), InlineData(LanguageVersion.CSharp10, LanguageVersion.LatestMajor), InlineData(LanguageVersion.CSharp10, LanguageVersion.Latest), InlineData(LanguageVersion.CSharp10, LanguageVersion.Default), InlineData(LanguageVersion.Preview, LanguageVersion.Preview), ] public void LanguageVersion_MapSpecifiedToEffectiveVersion(LanguageVersion expectedMappedVersion, LanguageVersion input) { Assert.Equal(expectedMappedVersion, input.MapSpecifiedToEffectiveVersion()); Assert.True(expectedMappedVersion.IsValid()); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData("iso-1", true, LanguageVersion.CSharp1), InlineData("ISO-1", true, LanguageVersion.CSharp1), InlineData("iso-2", true, LanguageVersion.CSharp2), InlineData("1", true, LanguageVersion.CSharp1), InlineData("1.0", true, LanguageVersion.CSharp1), InlineData("2", true, LanguageVersion.CSharp2), InlineData("2.0", true, LanguageVersion.CSharp2), InlineData("3", true, LanguageVersion.CSharp3), InlineData("3.0", true, LanguageVersion.CSharp3), InlineData("4", true, LanguageVersion.CSharp4), InlineData("4.0", true, LanguageVersion.CSharp4), InlineData("5", true, LanguageVersion.CSharp5), InlineData("5.0", true, LanguageVersion.CSharp5), InlineData("05", false, LanguageVersion.Default), InlineData("6", true, LanguageVersion.CSharp6), InlineData("6.0", true, LanguageVersion.CSharp6), InlineData("7", true, LanguageVersion.CSharp7), InlineData("7.0", true, LanguageVersion.CSharp7), InlineData("07", false, LanguageVersion.Default), InlineData("7.1", true, LanguageVersion.CSharp7_1), InlineData("7.2", true, LanguageVersion.CSharp7_2), InlineData("7.3", true, LanguageVersion.CSharp7_3), InlineData("8", true, LanguageVersion.CSharp8), InlineData("8.0", true, LanguageVersion.CSharp8), InlineData("9", true, LanguageVersion.CSharp9), InlineData("9.0", true, LanguageVersion.CSharp9), InlineData("10", true, LanguageVersion.CSharp10), InlineData("10.0", true, LanguageVersion.CSharp10), InlineData("08", false, LanguageVersion.Default), InlineData("07.1", false, LanguageVersion.Default), InlineData("default", true, LanguageVersion.Default), InlineData("latest", true, LanguageVersion.Latest), InlineData("latestmajor", true, LanguageVersion.LatestMajor), InlineData("preview", true, LanguageVersion.Preview), InlineData("latestpreview", false, LanguageVersion.Default), InlineData(null, true, LanguageVersion.Default), InlineData("bad", false, LanguageVersion.Default)] public void LanguageVersion_TryParseDisplayString(string input, bool success, LanguageVersion expected) { Assert.Equal(success, LanguageVersionFacts.TryParse(input, out var version)); Assert.Equal(expected, version); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Fact] public void LanguageVersion_TryParseTurkishDisplayString() { var originalCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR", useUserOverride: false); Assert.True(LanguageVersionFacts.TryParse("ISO-1", out var version)); Assert.Equal(LanguageVersion.CSharp1, version); Thread.CurrentThread.CurrentCulture = originalCulture; } [Fact] public void LangVersion_ListLangVersions() { var dir = Temp.CreateDirectory(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/langversion:?" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var expected = Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>() .Select(v => v.ToDisplayString()); var actual = outWriter.ToString(); var acceptableSurroundingChar = new[] { '\r', '\n', '(', ')', ' ' }; foreach (var version in expected) { if (version == "latest") continue; var foundIndex = actual.IndexOf(version); Assert.True(foundIndex > 0, $"Missing version '{version}'"); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex - 1]) >= 0); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex + version.Length]) >= 0); } } [Fact] [WorkItem(546961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546961")] public void Define() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;BAR,ZIP", "a.cs" }, WorkingDirectory); Assert.Equal(3, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("BAR", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("ZIP", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;4X", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.WRN_DefineIdentifierRequired, parsedArgs.Errors.First().Code); Assert.Equal("4X", parsedArgs.Errors.First().Arguments[0]); IEnumerable<Diagnostic> diagnostics; // The docs say /d:def1[;def2] string compliant = "def1;def2;def3"; var expected = new[] { "def1", "def2", "def3" }; var parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // Bug 17360: Dev11 allows for a terminating semicolon var dev11Compliant = "def1;def2;def3;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // And comma dev11Compliant = "def1,def2,def3,"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // This breaks everything var nonCompliant = "def1;;def2;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(nonCompliant, out diagnostics); diagnostics.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("")); Assert.Equal(new[] { "def1", "def2" }, parsed); // Bug 17360 parsedArgs = DefaultParse(new[] { "/d:public1;public2;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Fact] public void Debug() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:FULL", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.PortablePdb, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:PDBONLY", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "debug")); parsedArgs = DefaultParse(new[] { "/debug:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("+")); parsedArgs = DefaultParse(new[] { "/debug:invalid", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("invalid")); parsedArgs = DefaultParse(new[] { "/debug-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/debug-:")); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Pdb() { var parsedArgs = DefaultParse(new[] { "/pdb:something", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug:embedded", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.PdbPath); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb")); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb:", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb:")); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // temp: path changed //parsedArgs = DefaultParse(new[] { "/debug", "/pdb:.x", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); parsedArgs = DefaultParse(new[] { @"/pdb:""""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/pdb:""' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(@"/pdb:""""").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/pdb:C:\\", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("C:\\")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:C:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyPdb.pdb", parsedArgs.PdbPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:c:\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"c:\MyPdb.pdb", parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(Path.GetPathRoot(WorkingDirectory), @"MyFolder\MyPdb.pdb"), parsedArgs.PdbPath); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/pdb:""C:\My Folder\MyPdb.pdb""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyPdb.pdb", parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", WorkingDirectory), parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:..\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Temp: Path info changed // Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", "..\\", baseDirectory), parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b\OkFileName.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b\OkFileName.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\server\share\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\MyPdb.pdb", parsedArgs.PdbPath); // invalid name: parsedArgs = DefaultParse(new[] { "/pdb:a.b\0b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:a\uD800b.pdb", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.pdb")); Assert.Null(parsedArgs.PdbPath); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/pdb:""a<>.pdb""", "a.vb" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:.x", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.PdbPath); } [Fact] public void SourceLink() { var parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { @"/sourcelink:""s l.json""", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "s l.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); } [Fact] public void SourceLink_EndToEnd_EmbeddedPortable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:embedded", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var peStream = File.OpenRead(Path.Combine(dir.Path, "a.exe")); using (var peReader = new PEReader(peStream)) { var entry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); using (var mdProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Portable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:portable", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); using (var mdProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Windows() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); byte[] slContent = Encoding.UTF8.GetBytes(@"{ ""documents"" : {} }"); sl.WriteAllBytes(slContent); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:full", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); var actualData = PdbValidation.GetSourceLinkData(pdbStream); AssertEx.Equal(slContent, actualData); // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void Embed() { var parsedArgs = DefaultParse(new[] { "a.cs " }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Empty(parsedArgs.EmbeddedFiles); parsedArgs = DefaultParse(new[] { "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(parsedArgs.SourceFiles, parsedArgs.EmbeddedFiles); AssertEx.Equal( new[] { "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs", "/embed:b.cs", "/debug:embedded", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs;b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs,b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { @"/embed:""a,b.cs""", "/debug:portable", "a,b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a,b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); ; AssertEx.Equal( new[] { "a.txt", "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Theory] [InlineData("/debug:portable", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:portable", "/embed:embed.xyz", new[] { "embed.xyz" })] [InlineData("/debug:embedded", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:embedded", "/embed:embed.xyz", new[] { "embed.xyz" })] public void Embed_EndToEnd_Portable(string debugSwitch, string embedSwitch, string[] expectedEmbedded) { // embed.cs: large enough to compress, has #line directives const string embed_cs = @"/////////////////////////////////////////////////////////////////////////////// class Program { static void Main() { #line 1 ""embed.xyz"" System.Console.WriteLine(""Hello, World""); #line 3 System.Console.WriteLine(""Goodbye, World""); } } ///////////////////////////////////////////////////////////////////////////////"; // embed2.cs: small enough to not compress, no sequence points const string embed2_cs = @"class C { }"; // target of #line const string embed_xyz = @"print Hello, World print Goodbye, World"; Assert.True(embed_cs.Length >= EmbeddedText.CompressionThreshold); Assert.True(embed2_cs.Length < EmbeddedText.CompressionThreshold); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("embed.cs"); var src2 = dir.CreateFile("embed2.cs"); var txt = dir.CreateFile("embed.xyz"); src.WriteAllText(embed_cs); src2.WriteAllText(embed2_cs); txt.WriteAllText(embed_xyz); var expectedEmbeddedMap = new Dictionary<string, string>(); if (expectedEmbedded.Contains("embed.cs")) { expectedEmbeddedMap.Add(src.Path, embed_cs); } if (expectedEmbedded.Contains("embed2.cs")) { expectedEmbeddedMap.Add(src2.Path, embed2_cs); } if (expectedEmbedded.Contains("embed.xyz")) { expectedEmbeddedMap.Add(txt.Path, embed_xyz); } var output = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", debugSwitch, embedSwitch, "embed.cs", "embed2.cs" }); int exitCode = csc.Run(output); Assert.Equal("", output.ToString().Trim()); Assert.Equal(0, exitCode); switch (debugSwitch) { case "/debug:embedded": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: true); break; case "/debug:portable": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: false); break; case "/debug:full": ValidateEmbeddedSources_Windows(expectedEmbeddedMap, dir); break; } Assert.Empty(expectedEmbeddedMap); CleanupAllGeneratedFiles(src.Path); } private static void ValidateEmbeddedSources_Portable(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir, bool isEmbeddedPdb) { using (var peReader = new PEReader(File.OpenRead(Path.Combine(dir.Path, "embed.exe")))) { var entry = peReader.ReadDebugDirectory().SingleOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); Assert.Equal(isEmbeddedPdb, entry.DataSize > 0); using (var mdProvider = isEmbeddedPdb ? peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry) : MetadataReaderProvider.FromPortablePdbStream(File.OpenRead(Path.Combine(dir.Path, "embed.pdb")))) { var mdReader = mdProvider.GetMetadataReader(); foreach (var handle in mdReader.Documents) { var doc = mdReader.GetDocument(handle); var docPath = mdReader.GetString(doc.Name); SourceText embeddedSource = mdReader.GetEmbeddedSource(handle); if (embeddedSource == null) { continue; } Assert.Equal(expectedEmbeddedMap[docPath], embeddedSource.ToString()); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } } } private static void ValidateEmbeddedSources_Windows(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir) { ISymUnmanagedReader5 symReader = null; try { symReader = SymReaderFactory.CreateReader(File.OpenRead(Path.Combine(dir.Path, "embed.pdb"))); foreach (var doc in symReader.GetDocuments()) { var docPath = doc.GetName(); var sourceBlob = doc.GetEmbeddedSource(); if (sourceBlob.Array == null) { continue; } var sourceStr = Encoding.UTF8.GetString(sourceBlob.Array, sourceBlob.Offset, sourceBlob.Count); Assert.Equal(expectedEmbeddedMap[docPath], sourceStr); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } catch { symReader?.Dispose(); } } private static void ValidateWrittenSources(Dictionary<string, Dictionary<string, string>> expectedFilesMap, Encoding encoding = null) { foreach ((var dirPath, var fileMap) in expectedFilesMap.ToArray()) { foreach (var file in Directory.GetFiles(dirPath)) { var name = Path.GetFileName(file); var content = File.ReadAllText(file, encoding ?? Encoding.UTF8); Assert.Equal(fileMap[name], content); Assert.True(fileMap.Remove(name)); } Assert.Empty(fileMap); Assert.True(expectedFilesMap.Remove(dirPath)); } Assert.Empty(expectedFilesMap); } [Fact] public void Optimize() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(new CSharpCompilationOptions(OutputKind.ConsoleApplication).OptimizationLevel, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:+")); parsedArgs = DefaultParse(new[] { "/optimize:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:")); parsedArgs = DefaultParse(new[] { "/optimize-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize-:")); parsedArgs = DefaultParse(new[] { "/o-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "/optimize-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:+")); parsedArgs = DefaultParse(new string[] { "/o:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:")); parsedArgs = DefaultParse(new string[] { "/o-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o-:")); } [Fact] public void Deterministic() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); } [Fact] public void ParseReferences() { var parsedArgs = DefaultParse(new string[] { "/r:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); parsedArgs = DefaultParse(new string[] { "/r:goo.dll;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/l:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/addmodule:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/r:a=goo.dll", "/l:b=bar.dll", "/addmodule:c=mod.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(4, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "a" }), parsedArgs.MetadataReferences[1].Properties); Assert.Equal("bar.dll", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "b" }).WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[2].Properties); Assert.Equal("c=mod.dll", parsedArgs.MetadataReferences[3].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[3].Properties); // TODO: multiple files, quotes, etc. } [Fact] public void ParseAnalyzers() { var parsedArgs = DefaultParse(new string[] { @"/a:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/analyzer:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { "/analyzer:\"goo.dll\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:goo.dll;bar.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); Assert.Equal("bar.dll", parsedArgs.AnalyzerReferences[1].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/a:")); parsedArgs = DefaultParse(new string[] { "/a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/a")); } [Fact] public void Analyzers_Missing() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/a:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_Empty() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + typeof(object).Assembly.Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.DoesNotContain("warning", outWriter.ToString()); CleanupAllGeneratedFiles(file.Path); } private TempFile CreateRuleSetFile(string source) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); return file; } [Fact] public void RuleSetSwitchPositive() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1012")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1012"] == ReportDiagnostic.Error); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1013")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1013"] == ReportDiagnostic.Warn); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1014")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1014"] == ReportDiagnostic.Suppress); Assert.True(parsedArgs.CompilationOptions.GeneralDiagnosticOption == ReportDiagnostic.Warn); } [Fact] public void RuleSetSwitchQuoted() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + "\"" + file.Path + "\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); } [Fact] public void RuleSetSwitchParseErrors() { var parsedArgs = DefaultParse(new string[] { @"/ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah"), actual: parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah;blah.ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah;blah.ruleset"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah;blah.ruleset"), actual: parsedArgs.RuleSetPath); var file = CreateRuleSetFile("Random text"); parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(file.Path, "Data at the root level is invalid. Line 1, position 1.")); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); var err = parsedArgs.Errors.Single(); Assert.Equal((int)ErrorCode.ERR_CantReadRulesetFile, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal(file.Path, (string)err.Arguments[0]); var currentUICultureName = Thread.CurrentThread.CurrentUICulture.Name; if (currentUICultureName.Length == 0 || currentUICultureName.StartsWith("en", StringComparison.OrdinalIgnoreCase)) { Assert.Equal("Data at the root level is invalid. Line 1, position 1.", (string)err.Arguments[1]); } } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void Analyzers_Found() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic thrown Assert.True(outWriter.ToString().Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared")); // Diagnostic cannot be instantiated Assert.True(outWriter.ToString().Contains("warning CS8032")); CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_WithRuleSet() { string source = @" class C { int x; } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error. Assert.True(outWriter.ToString().Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared")); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warnaserror+", "/nowarn:8032" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warnaserror+", "/ruleset:" + ruleSetFile.Path, "/nowarn:8032" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Info); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test002", "/warnaserror-:Test002", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test002"], expected: ReportDiagnostic.Default); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesGeneralWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesSpecificWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_Capitalization() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:NullABLE", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_MultipleArguments() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable,Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 3, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void WarnAsError_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/warnaserror:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warn:0" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warn:0", "/ruleset:" + ruleSetFile.Path }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void DiagnosticFormatting() { string source = @" using System; class C { public static void Main() { Goo(0); #line 10 ""c:\temp\a\1.cs"" Goo(1); #line 20 ""C:\a\..\b.cs"" Goo(2); #line 30 ""C:\a\../B.cs"" Goo(3); #line 40 ""../b.cs"" Goo(4); #line 50 ""..\b.cs"" Goo(5); #line 60 ""C:\X.cs"" Goo(6); #line 70 ""C:\x.cs"" Goo(7); #line 90 "" "" Goo(9); #line 100 ""C:\*.cs"" Goo(10); #line 110 """" Goo(11); #line hidden Goo(12); #line default Goo(13); #line 140 ""***"" Goo(14); } } "; var dir = Temp.CreateDirectory(); dir.CreateFile("a.cs").WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // with /fullpaths off string expected = @" a.cs(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context a.cs(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); // with /fullpaths on outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/fullpaths", "a.cs" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); expected = @" " + Path.Combine(dir.Path, @"a.cs") + @"(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.Combine(dir.Path, @"a.cs") + @"(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); } [WorkItem(540891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540891")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseOut() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/out:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '' contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("")); parsedArgs = DefaultParse(new[] { @"/out:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out:")); parsedArgs = DefaultParse(new[] { @"/refout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/refout:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/refout:")); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/refonly", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8301: Do not use refout when using refonly. Diagnostic(ErrorCode.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly:incorrect", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/refonly:incorrect' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/refonly:incorrect").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refonly", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); // Dev11 reports CS2007: Unrecognized option: '/out' parsedArgs = DefaultParse(new[] { @"/out", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out")); parsedArgs = DefaultParse(new[] { @"/out+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/out+")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/out:C:\MyFolder\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\MyFolder", parsedArgs.OutputDirectory); Assert.Equal(@"C:\MyFolder\MyBinary.dll", parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/out:""C:\My Folder\MyBinary.dll""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\My Folder", parsedArgs.OutputDirectory); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.dll"), parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:..\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\abc\def", parsedArgs.OutputDirectory); // not specified: exe parsedArgs = DefaultParse(new[] { @"a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: dll parsedArgs = DefaultParse(new[] { @"/target:library", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.dll", parsedArgs.OutputFileName); Assert.Equal("a.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: module parsedArgs = DefaultParse(new[] { @"/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: appcontainerexe parsedArgs = DefaultParse(new[] { @"/target:appcontainerexe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: winmdobj parsedArgs = DefaultParse(new[] { @"/target:winmdobj", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.winmdobj", parsedArgs.OutputFileName); Assert.Equal("a.winmdobj", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { currentDrive + @":a.cs", "b.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.cs' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.cs")); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // UNC parsedArgs = DefaultParse(new[] { @"/out:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:\\server\share\file.exe", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share", parsedArgs.OutputDirectory); Assert.Equal("file.exe", parsedArgs.OutputFileName); Assert.Equal("file", parsedArgs.CompilationName); Assert.Equal("file.exe", parsedArgs.CompilationOptions.ModuleName); // invalid name: parsedArgs = DefaultParse(new[] { "/out:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); // Temporary skip following scenarios because of the error message changed (path) //parsedArgs = DefaultParse(new[] { "/out:a\uD800b.dll", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.dll")); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/out:""a<>.dll""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.dll")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", @"/out:.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", @"/out:.netmodule", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.netmodule' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".netmodule") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", ".cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(".netmodule", parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName); } [WorkItem(546012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546012")] [WorkItem(546007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546007")] [Fact] public void ParseOut2() { var parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); } [Fact] public void ParseInstrumentTestNames() { var parsedArgs = DefaultParse(SpecializedCollections.EmptyEnumerable<string>(), WorkingDirectory); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:""""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:", "Test.Flag.Name", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:None", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("None")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TestCoverage""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TESTCOVERAGE""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseDoc() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/doc:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); // NOTE: no colon in error message '/doc' parsedArgs = DefaultParse(new[] { @"/doc", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/doc+")); Assert.Null(parsedArgs.DocumentationPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/doc:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/doc:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/doc:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // UNC parsedArgs = DefaultParse(new[] { @"/doc:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // invalid name: parsedArgs = DefaultParse(new[] { "/doc:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // Temp // parsedArgs = DefaultParse(new[] { "/doc:a\uD800b.xml", "a.cs" }, baseDirectory); // parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.xml")); // Assert.Null(parsedArgs.DocumentationPath); // Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseErrorLog() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/errorlog:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Escaped quote in the middle is an error parsedArgs = DefaultParse(new[] { @"/errorlog:C:\""My Folder""\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"C:""My Folder\MyBinary.xml").WithLocation(1, 1)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/errorlog:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/errorlog:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // UNC parsedArgs = DefaultParse(new[] { @"/errorlog:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.ErrorLogOptions.Path); // invalid name: parsedArgs = DefaultParse(new[] { "/errorlog:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Parses SARIF version. parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml,version=2", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(SarifVersion.Sarif2, parsedArgs.ErrorLogOptions.SarifVersion); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Invalid SARIF version. string[] invalidSarifVersions = new string[] { @"C:\MyFolder\MyBinary.xml,version=1.0.0", @"C:\MyFolder\MyBinary.xml,version=2.1.0", @"C:\MyFolder\MyBinary.xml,version=42" }; foreach (string invalidSarifVersion in invalidSarifVersions) { parsedArgs = DefaultParse(new[] { $"/errorlog:{invalidSarifVersion}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(invalidSarifVersion, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } // Invalid errorlog qualifier. const string InvalidErrorLogQualifier = @"C:\MyFolder\MyBinary.xml,invalid=42"; parsedArgs = DefaultParse(new[] { $"/errorlog:{InvalidErrorLogQualifier}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,invalid=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(InvalidErrorLogQualifier, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Too many errorlog qualifiers. const string TooManyErrorLogQualifiers = @"C:\MyFolder\MyBinary.xml,version=2,version=2"; parsedArgs = DefaultParse(new[] { $"/errorlog:{TooManyErrorLogQualifiers}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=2,version=2' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(TooManyErrorLogQualifiers, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigParse() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/appconfig:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:a.exe.config", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a.exe.config", parsedArgs.AppConfigPath); // If ParseDoc succeeds, all other possible AppConfig paths should succeed as well -- they both call ParseGenericFilePath } [Fact] public void AppConfigBasic() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var appConfigFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>"); var silverlight = Temp.CreateFile().WriteAllBytes(ProprietaryTestResources.silverlight_v5_0_5_0.System_v5_0_5_0_silverlight).Path; var net4_0dll = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; // Test linking two appconfig dlls with simple src var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/r:" + silverlight, "/r:" + net4_0dll, "/appconfig:" + appConfigFile.Path, srcFile.Path }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(appConfigFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigBasicFail() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); string root = Path.GetPathRoot(srcDirectory); // Make sure we pick a drive that exists and is plugged in to avoid 'Drive not ready' var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/preferreduilang:en", $@"/appconfig:{root}DoesNotExist\NOwhere\bonobo.exe.config" , srcFile.Path }).Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal($@"error CS7093: Cannot read config file '{root}DoesNotExist\NOwhere\bonobo.exe.config' -- 'Could not find a part of the path '{root}DoesNotExist\NOwhere\bonobo.exe.config'.'", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void ParseDocAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and XML output. var parsedArgs = DefaultParse(new[] { @"/doc:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/doc:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [ConditionalFact(typeof(WindowsOnly))] public void ParseErrorLogAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and error log output. var parsedArgs = DefaultParse(new[] { @"/errorlog:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/errorlog:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [Fact] public void ModuleAssemblyName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:exe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); } [Fact] public void ModuleName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/modulename:bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("bar", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:CommonLanguageRuntimeLibrary", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("CommonLanguageRuntimeLibrary", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'modulename' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "modulename").WithLocation(1, 1) ); } [Fact] public void ModuleName001() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); file1.WriteAllText(@" class c1 { public static void Main(){} } "); var exeName = "aa.exe"; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/modulename:hocusPocus ", "/out:" + exeName + " ", file1.Path }); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, exeName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, "aa.exe")))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal("aa", peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal("hocusPocus", peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(exeName)) { System.IO.File.Delete(exeName); } CleanupAllGeneratedFiles(file1.Path); } [Fact] public void ParsePlatform() { var parsedArgs = DefaultParse(new[] { @"/platform:x64", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X64, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:X86", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X86, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:itanum", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadPlatformType, parsedArgs.Errors.First().Code); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:itanium", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Itanium, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu32bitpreferred", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:arm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Arm, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default parsedArgs = DefaultParse(new[] { "/platform:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform:")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default } [WorkItem(546016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546016")] [WorkItem(545997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545997")] [WorkItem(546019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546019")] [WorkItem(546029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546029")] [Fact] public void ParseBaseAddress() { var parsedArgs = DefaultParse(new[] { @"/baseaddress:x64", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(0x8000000000011111ul, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x86", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:-23", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:01777777777777777777777", "a.cs" }, WorkingDirectory); Assert.Equal(ulong.MaxValue, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x0000000100000000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0xffff8000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffffffff" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFFFFFF")); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x86", "/baseaddress:0xffff7fff" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x100000000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x10000000000000000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0x10000000000000000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); } [Fact] public void ParseFileAlignment() { var parsedArgs = DefaultParse(new[] { @"/filealign:x64", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number 'x64' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("x64")); parsedArgs = DefaultParse(new[] { @"/filealign:0x200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(0x200, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:512", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'filealign' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("filealign")); parsedArgs = DefaultParse(new[] { @"/filealign:-23", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '-23' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("-23")); parsedArgs = DefaultParse(new[] { @"/filealign:020000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '0' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("0")); parsedArgs = DefaultParse(new[] { @"/filealign:123", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '123' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("123")); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable() { var dir = Temp.CreateDirectory(); var lib1 = dir.CreateDirectory("lib1"); var lib2 = dir.CreateDirectory("lib2"); var lib3 = dir.CreateDirectory("lib3"); var sdkDirectory = SdkDirectory; var parsedArgs = DefaultParse(new[] { @"/lib:lib1", @"/libpath:lib2", @"/libpaths:lib3", "a.cs" }, dir.Path, sdkDirectory: sdkDirectory); AssertEx.Equal(new[] { sdkDirectory, lib1.Path, lib2.Path, lib3.Path }, parsedArgs.ReferencePaths); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable_Errors() { var parsedArgs = DefaultParse(new[] { @"/lib:c:lib2", @"/lib:o:\sdk1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'c:lib2' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"c:lib2", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path 'o:\sdk1' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\sdk1", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e:", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,.\Windows;e;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path '.\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@".\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:; ; ; ; ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("e:", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/lib+")); parsedArgs = DefaultParse(new[] { @"/lib: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); } [Fact, WorkItem(546005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546005")] public void SdkPathAndLibEnvVariable_Relative_csc() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var subDirectory = subFolder.ToString(); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, subDirectory, new[] { "/nologo", "/t:library", "/out:abc.xyz", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/lib:temp", "/r:abc.xyz", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } [Fact] public void UnableWriteOutput() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/out:" + subFolder.ToString(), src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.True(outWriter.ToString().Trim().StartsWith("error CS2012: Cannot open '" + subFolder.ToString() + "' for writing -- '", StringComparison.Ordinal)); // Cannot create a file when that file already exists. CleanupAllGeneratedFiles(src.Path); } [Fact] public void ParseHighEntropyVA() { var parsedArgs = DefaultParse(new[] { @"/highentropyva", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva+", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:-", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); //last one wins parsedArgs = DefaultParse(new[] { @"/highenTROPyva+", @"/HIGHentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); } [Fact] public void Checked() { var parsedArgs = DefaultParse(new[] { @"/checked+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checked:")); } [Fact] public void Nullable() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1)); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:eNable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disablE", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'Safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("Safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yeS", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yeS' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yeS").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:8" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:7.3" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:""safeonly""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\""enable\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '"enable"' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\"enable\"").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\disable\\", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\\disable\\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\\\disable\\\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\""enable\\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\enable\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\enable\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonlywarnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlywarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlywarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:SafeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'SafeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("SafeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:warnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Warnings' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:annotations", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); } [Fact] public void Usings() { CSharpCommandLineArguments parsedArgs; var sdkDirectory = SdkDirectory; parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar;Baz", "/using:System.Core;System" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar", "Baz", "System.Core", "System" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo;;Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo", "Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<namespace>' for '/u:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<namespace>", "/u:")); } [Fact] public void WarningsErrors() { var parsedArgs = DefaultParse(new string[] { "/nowarn", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); parsedArgs = DefaultParse(new string[] { "/nowarn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/nowarn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'warnaserror' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror")); parsedArgs = DefaultParse(new string[] { "/warnaserror:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:70000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror+:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror+:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror+")); parsedArgs = DefaultParse(new string[] { "/warnaserror-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror-:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror-")); parsedArgs = DefaultParse(new string[] { "/w", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/warn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warn:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/w:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/warn:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/warnaserror:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1;2;;3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } private static void AssertSpecificDiagnostics(int[] expectedCodes, ReportDiagnostic[] expectedOptions, CSharpCommandLineArguments args) { var actualOrdered = args.CompilationOptions.SpecificDiagnosticOptions.OrderBy(entry => entry.Key); AssertEx.Equal( expectedCodes.Select(i => MessageProvider.Instance.GetIdForErrorCode(i)), actualOrdered.Select(entry => entry.Key)); AssertEx.Equal(expectedOptions, actualOrdered.Select(entry => entry.Value)); } [Fact] public void WarningsParse() { var parsedArgs = DefaultParse(new string[] { "/warnaserror", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(0, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); parsedArgs = DefaultParse(new string[] { "/warnaserror:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:+1062,+1066,+1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1762,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics( new[] { 1062, 1066, 1734, 1762, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(4, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/w:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { @"/nowarn:""1062 1066 1734""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "/warnaserror:1066,1762", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:1066,1762", "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); } [Fact] public void AllowUnsafe() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/unsafe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/UNSAFE-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe-", "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); // default parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:")); parsedArgs = DefaultParse(new[] { "/unsafe:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:+")); parsedArgs = DefaultParse(new[] { "/unsafe-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe-:")); } [Fact] public void DelaySign() { CSharpCommandLineArguments parsedArgs; parsedArgs = DefaultParse(new[] { "/delaysign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/DELAYsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.False((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/delaysign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/delaysign:-")); Assert.Null(parsedArgs.CompilationOptions.DelaySign); } [Fact] public void PublicSign() { var parsedArgs = DefaultParse(new[] { "/publicsign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/PUBLICsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/publicsign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/publicsign:-").WithLocation(1, 1)); Assert.False(parsedArgs.CompilationOptions.PublicSign); } [WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")] [Fact] public void PublicSign_KeyFileRelativePath() { var parsedArgs = DefaultParse(new[] { "/publicsign", "/keyfile:test.snk", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "test.snk"), parsedArgs.CompilationOptions.CryptoKeyFile); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath() { DefaultParse(new[] { "/publicsign", "/keyfile:", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath2() { DefaultParse(new[] { "/publicsign", "/keyfile:\"\"", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [WorkItem(546301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546301")] [Fact] public void SubsystemVersionTests() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(4, 0), parsedArgs.EmitOptions.SubsystemVersion); // wrongly supported subsystem version. CompilationOptions data will be faithful to the user input. // It is normalized at the time of emit. parsedArgs = DefaultParse(new[] { "/subsystemversion:0.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:3.99", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(3, 99), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "/SUBsystemversion:5.333", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(5, 333), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/subsystemversion-")); parsedArgs = DefaultParse(new[] { "/subsystemversion: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion: 4.1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(" 4.1")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4 .0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4 .0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4. 0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4. 0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.2 ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.65536", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.65536")); parsedArgs = DefaultParse(new[] { "/subsystemversion:65536.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("65536.0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:-4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("-4.0")); // TODO: incompatibilities: versions lower than '6.2' and 'arm', 'winmdobj', 'appcontainer' } [Fact] public void MainType() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/m:A.B.C", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("A.B.C", parsedArgs.CompilationOptions.MainTypeName); parsedArgs = DefaultParse(new[] { "/m: ", "a.cs" }, WorkingDirectory); // Mimicking Dev11 parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); Assert.Null(parsedArgs.CompilationOptions.MainTypeName); // overriding the value parsedArgs = DefaultParse(new[] { "/m:A.B.C", "/MAIN:X.Y.Z", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("X.Y.Z", parsedArgs.CompilationOptions.MainTypeName); // error parsedArgs = DefaultParse(new[] { "/maiN:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "main")); parsedArgs = DefaultParse(new[] { "/MAIN+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/MAIN+")); parsedArgs = DefaultParse(new[] { "/M", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); // incompatible values /main && /target parsedArgs = DefaultParse(new[] { "/main:a", "/t:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); parsedArgs = DefaultParse(new[] { "/main:a", "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); } [Fact] public void Codepage() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/CodePage:1200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode", parsedArgs.Encoding.EncodingName); parsedArgs = DefaultParse(new[] { "/CodePage:1200", "/codePAGE:65001", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode (UTF-8)", parsedArgs.Encoding.EncodingName); // error parsedArgs = DefaultParse(new[] { "/codepage:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("0")); parsedArgs = DefaultParse(new[] { "/codepage:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("abc")); parsedArgs = DefaultParse(new[] { "/codepage:-5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("-5")); parsedArgs = DefaultParse(new[] { "/codepage: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "codepage")); parsedArgs = DefaultParse(new[] { "/codepage+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/codepage+")); } [Fact, WorkItem(24735, "https://github.com/dotnet/roslyn/issues/24735")] public void ChecksumAlgorithm() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sHa1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha1, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); // error parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("256")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha-1")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checksumAlgorithm+")); } [Fact] public void AddModule() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/addmodule:abc.netmodule", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.MetadataReferences.Length); Assert.Equal("abc.netmodule", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/aDDmodule:c:\\abc;c:\\abc;d:\\xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(3, parsedArgs.MetadataReferences.Length); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[1].Properties.Kind); Assert.Equal("d:\\xyz", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[2].Properties.Kind); // error parsedArgs = DefaultParse(new[] { "/ADDMODULE", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/addmodule:")); parsedArgs = DefaultParse(new[] { "/ADDMODULE+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/ADDMODULE+")); parsedArgs = DefaultParse(new[] { "/ADDMODULE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/ADDMODULE:")); } [Fact, WorkItem(530751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530751")] public void CS7061fromCS0647_ModuleWithCompilationRelaxations() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] public class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(4)] public class Mod { }").Path; string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] class Test { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source); // === Scenario 1 === var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); var parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Empty(outWriter.ToString()); // === Scenario 2 === outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source2 }).Run(outWriter); Assert.Equal(0, exitCode); modfile = source2.Substring(0, source2.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Equal(1, exitCode); // Dev11: CS0647 (Emit) Assert.Contains("error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(530780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530780")] public void AddModuleWithExtensionMethod() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"public static class Extensions { public static bool EB(this bool b) { return b; } }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source2 }).Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact, WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")] public void OLDCS0013FTL_MetadataEmitFailureSameModAndRes() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, "/linkres:" + modfile, source2 }).Run(outWriter); Assert.Equal(1, exitCode); // Native gives CS0013 at emit stage Assert.Equal("error CS7041: Each linked resource and module must have a unique filename. Filename '" + Path.GetFileName(modfile) + "' is specified more than once in this assembly", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact] public void Utf8Output() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output", "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/utf8output:")); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesRunnableProgram() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); string output = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.RunAndGetOutput("cmd.exe", $@"/C ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir) : ProcessUtilities.RunAndGetOutput("sh", $@"-c ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir); Assert.Equal("Hello World!", output.Trim()); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesLibrary() { var name = Guid.NewGuid().ToString() + ".dll"; string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public A Get() =^^^> default; ^ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public A Get\(\) =\> default\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); var assemblyName = AssemblyName.GetAssemblyName(Path.Combine(tempDir, name)); Assert.Equal(name.Replace(".dll", ", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), assemblyName.ToString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/55727")] public void CsiScript_WithSourceCodeRedirectedViaStandardInput_ExecutesNonInteractively() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo Console.WriteLine(""Hello World!"") | {s_CSharpScriptExecutable} -") : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo Console.WriteLine\(\\\""Hello World\!\\\""\) | {s_CSharpScriptExecutable} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); Assert.Equal("Hello World!", result.Output.Trim()); } [Fact] public void CscCompile_WithRedirectedInputIndicatorAndStandardInputNotRedirected_ReportsCS8782() { if (Console.IsInputRedirected) { // [applicable to both Windows and Unix] // if our parent (xunit) process itself has input redirected, we cannot test this // error case because our child process will inherit it and we cannot achieve what // we are aiming for: isatty(0):true and thereby Console.IsInputerRedirected:false in // child. running this case will make StreamReader to hang (waiting for input, that // we do not propagate: parent.In->child.In). // // note: in Unix we can "close" fd0 by appending `0>&-` in the `sh -c` command below, // but that will also not impact the result of isatty(), and in turn causes a different // compiler error. return; } string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir); Assert.True(result.ContainsErrors); Assert.Contains(((int)ErrorCode.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected).ToString(), result.Output); } [Fact] public void CscCompile_WithMultipleStdInOperators_WarnsCS2002() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -" .Replace(Environment.NewLine, string.Empty)) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.Contains(((int)ErrorCode.WRN_FileAlreadyIncluded).ToString(), result.Output); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_Off() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '?'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_On() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /utf8output /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '♚'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithModule() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:module /out:a.netmodule \"{aCs}\"", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /preferreduilang:en /t:module /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("warning CS2008: No source files specified.", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /resource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithLinkResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /linkresource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [Fact] public void KeyContainerAndKeyFile() { // KEYCONTAINER CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/keycontainer:RIPAdamYauch", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("RIPAdamYauch", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keycontainer-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keycontainer-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE parsedArgs = DefaultParse(new[] { @"/keyfile:\somepath\s""ome Fil""e.goo.bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); //EDMAURER let's not set the option in the event that there was an error. //Assert.Equal(@"\somepath\some File.goo.bar", parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyfile-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keyfile-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keyfile-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); // DEFAULTS parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE | KEYCONTAINER conflicts parsedArgs = DefaultParse(new[] { "/keyFile:a", "/keyContainer:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keyContainer:b", "/keyFile:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); } [Fact, WorkItem(554551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554551")] public void CS1698WRN_AssumedMatchThis() { // compile with: /target:library /keyfile:mykey.snk var text1 = @"[assembly:System.Reflection.AssemblyVersion(""2"")] public class CS1698_a {} "; // compile with: /target:library /reference:CS1698_a.dll /keyfile:mykey.snk var text2 = @"public class CS1698_b : CS1698_a {} "; //compile with: /target:library /out:cs1698_a.dll /reference:cs1698_b.dll /keyfile:mykey.snk var text = @"[assembly:System.Reflection.AssemblyVersion(""3"")] public class CS1698_c : CS1698_b {} public class CS1698_a {} "; var folder = Temp.CreateDirectory(); var cs1698a = folder.CreateFile("CS1698a.cs"); cs1698a.WriteAllText(text1); var cs1698b = folder.CreateFile("CS1698b.cs"); cs1698b.WriteAllText(text2); var cs1698 = folder.CreateFile("CS1698.cs"); cs1698.WriteAllText(text); var snkFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var kfile = "/keyfile:" + snkFile.Path; CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/t:library", kfile, "CS1698a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698a.Path, "CS1698b.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698b.Path, "/out:" + cs1698a.Path, "CS1698.cs" }, WorkingDirectory); // Roslyn no longer generates a warning for this...since this was only a warning, we're not really // saving anyone...does not provide high value to implement... // warning CS1698: Circular assembly reference 'CS1698a, Version=2.0.0.0, Culture=neutral,PublicKeyToken = 9e9d6755e7bb4c10' // does not match the output assembly name 'CS1698a, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10'. // Try adding a reference to 'CS1698a, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10' or changing the output assembly name to match. parsedArgs.Errors.Verify(); CleanupAllGeneratedFiles(snkFile.Path); CleanupAllGeneratedFiles(cs1698a.Path); CleanupAllGeneratedFiles(cs1698b.Path); CleanupAllGeneratedFiles(cs1698.Path); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30926")] public void BinaryFileErrorTest() { var binaryPath = Temp.CreateFile().WriteAllBytes(ResourcesNet451.mscorlib).Path; var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", binaryPath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( "error CS2015: '" + binaryPath + "' is a binary file instead of a text file", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(binaryPath); } #if !NETCOREAPP [WorkItem(530221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530221")] [WorkItem(5660, "https://github.com/dotnet/roslyn/issues/5660")] [ConditionalFact(typeof(WindowsOnly), typeof(IsEnglishLocal))] public void Bug15538() { // Several Jenkins VMs are still running with local systems permissions. This suite won't run properly // in that environment. Removing this check is being tracked by issue #79. using (var identity = System.Security.Principal.WindowsIdentity.GetCurrent()) { if (identity.IsSystem) { return; } // The icacls command fails on our Helix machines and it appears to be related to the use of the $ in // the username. // https://github.com/dotnet/roslyn/issues/28836 if (StringComparer.OrdinalIgnoreCase.Equals(Environment.UserDomainName, "WORKGROUP")) { return; } } var folder = Temp.CreateDirectory(); var source = folder.CreateFile("src.vb").WriteAllText("").Path; var _ref = folder.CreateFile("ref.dll").WriteAllText("").Path; try { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /inheritance:r /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + @" /deny %USERDOMAIN%\%USERNAME%:(r,WDAC) /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /r:" + _ref + " /t:library " + source, expectedRetCode: 1); Assert.Equal("error CS0009: Metadata file '" + _ref + "' could not be opened -- Access to the path '" + _ref + "' is denied.", output.Trim()); } finally { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /reset /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); File.Delete(_ref); } CleanupAllGeneratedFiles(source); } #endif [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="""" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileOrdering() { var rspFilePath1 = Temp.CreateFile().WriteAllText(@" /b /c ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d" }, new[] { "/a", @$"@""{rspFilePath1}""", "/d" }); var rspFilePath2 = Temp.CreateFile().WriteAllText(@" /c /d ").Path; rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b @""{rspFilePath2}"" ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", "/e" }); rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b ").Path; rspFilePath2 = Temp.CreateFile().WriteAllText(@" # this will be ignored /c /d ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", $@"@""{rspFilePath2}""", "/e" }); void assertOrder(string[] expected, string[] args) { var flattenedArgs = ArrayBuilder<string>.GetInstance(); var diagnostics = new List<Diagnostic>(); CSharpCommandLineParser.Default.FlattenArgs( args, diagnostics, flattenedArgs, scriptArgsOpt: null, baseDirectory: Path.DirectorySeparatorChar == '\\' ? @"c:\" : "/"); Assert.Empty(diagnostics); Assert.Equal(expected, flattenedArgs); flattenedArgs.Free(); } } [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference2() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="" "" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFile() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"" /d:""AA;BB"" /d:""N""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFileErr() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"""" /d:""AA;BB"" /d:""N"" ""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileSplitting() { string[] responseFile; responseFile = new string[] { @"a.cs b.cs ""c.cs e.cs""", @"hello world # this is a comment" }; IEnumerable<string> args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b.cs", @"c.cs e.cs", "hello", "world" }, args); // Check comment handling; comment character only counts at beginning of argument responseFile = new string[] { @" # ignore this", @" # ignore that ""hello""", @" a.cs #3.cs", @" b#.cs c#d.cs #e.cs", @" ""#f.cs""", @" ""#g.cs #h.cs""" }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b#.cs", "c#d.cs", "#f.cs", "#g.cs #h.cs" }, args); // Check backslash escaping responseFile = new string[] { @"a\b\c d\\e\\f\\ \\\g\\\h\\\i \\\\ \\\\\k\\\\\", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\b\c", @"d\\e\\f\\", @"\\\g\\\h\\\i", @"\\\\", @"\\\\\k\\\\\" }, args); // More backslash escaping and quoting responseFile = new string[] { @"a\""a b\\""b c\\\""c d\\\\""d e\\\\\""e f"" g""", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\""a", @"b\\""b c\\\""c d\\\\""d", @"e\\\\\""e", @"f"" g""" }, args); // Quoting inside argument is valid. responseFile = new string[] { @" /o:""goo.cs"" /o:""abc def""\baz ""/o:baz bar""bing", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"/o:""goo.cs""", @"/o:""abc def""\baz", @"""/o:baz bar""bing" }, args); } [ConditionalFact(typeof(WindowsOnly))] private void SourceFileQuoting() { string[] responseFile = new string[] { @"d:\\""abc def""\baz.cs ab""c d""e.cs", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); AssertEx.Equal(new[] { @"d:\abc def\baz.cs", @"c:\abc de.cs" }, args.SourceFiles.Select(file => file.Path)); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName1() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since DLL. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library" }, expectedOutputName: "p.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName2() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library", "/out:r.dll" }, expectedOutputName: "r.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName3() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName4() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName5() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:A" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName6() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:B" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName7() { string source1 = @" partial class A { static partial void Main() { } } "; string source2 = @" partial class A { static partial void Main(); } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName8() { string source1 = @" partial class A { static partial void Main(); } "; string source2 = @" partial class A { static partial void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName9() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since winmdobj. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:winmdobj" }, expectedOutputName: "p.winmdobj"); } [Fact] public void OutputFileName10() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since appcontainerexe. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:appcontainerexe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName_Switch() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [Fact] public void OutputFileName_NoEntryPoint() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal("error CS5001: Program does not contain a static 'Main' method suitable for an entry point", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact, WorkItem(1093063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1093063")] public void VerifyDiagnosticSeverityNotLocalized() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); // If "error" was localized, below assert will fail on PLOC builds. The output would be something like: "!pTCvB!vbc : !FLxft!error 表! CS5001:" Assert.Contains("error CS5001:", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(@"", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var patched = Regex.Replace(outWriter.ToString().Trim(), "version \\d+\\.\\d+\\.\\d+(-[\\w\\d]+)*", "version A.B.C-d"); patched = ReplaceCommitHash(patched); Assert.Equal(@" Microsoft (R) Visual C# Compiler version A.B.C-d (HASH) Copyright (C) Microsoft Corporation. All rights reserved.".Trim(), patched); CleanupAllGeneratedFiles(file.Path); } [Theory, InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (<developer build>)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (ABCDEF01)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (abcdef90)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (12345678)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)")] public void TestReplaceCommitHash(string orig, string expected) { Assert.Equal(expected, ReplaceCommitHash(orig)); } private static string ReplaceCommitHash(string s) { // open paren, followed by either <developer build> or 8 hex, followed by close paren return Regex.Replace(s, "(\\((<developer build>|[a-fA-F0-9]{8})\\))", "(HASH)"); } [Fact] public void ExtractShortCommitHash() { Assert.Null(CommonCompiler.ExtractShortCommitHash(null)); Assert.Equal("", CommonCompiler.ExtractShortCommitHash("")); Assert.Equal("<", CommonCompiler.ExtractShortCommitHash("<")); Assert.Equal("<developer build>", CommonCompiler.ExtractShortCommitHash("<developer build>")); Assert.Equal("1", CommonCompiler.ExtractShortCommitHash("1")); Assert.Equal("1234567", CommonCompiler.ExtractShortCommitHash("1234567")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("12345678")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("123456789")); } private void CheckOutputFileName(string source1, string source2, string inputName1, string inputName2, string[] commandLineArguments, string expectedOutputName) { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile(inputName1); file1.WriteAllText(source1); var file2 = dir.CreateFile(inputName2); file2.WriteAllText(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { inputName1, inputName2 }).ToArray()); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, "*" + PathUtilities.GetExtension(expectedOutputName)).Count()); Assert.Equal(1, Directory.EnumerateFiles(dir.Path, expectedOutputName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, expectedOutputName)))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(PathUtilities.RemoveExtension(expectedOutputName), peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(expectedOutputName, peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(expectedOutputName)) { System.IO.File.Delete(expectedOutputName); } CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); } [Fact] public void MissingReference() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/r:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_01() { string source = @" public class C { public static void Main() { } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect to be success, since there will be no warning) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:1 (expect success) // Note that even though the command line option has a warning, it is not going to become an error // in order to avoid the halt of compilation. exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror", "/nowarn:1" }); Assert.Equal(0, exitCode); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_02() { string source = @" public class C { public static void Main() { int x; // CS0168 } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect failure) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:168 (expect failure) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:168" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:219 (expect success) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:219" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:168 (expect success) exitCode = GetExitCode(source, "d.cs", new[] { "/warnaserror", "/nowarn:168" }); Assert.Equal(0, exitCode); } private int GetExitCode(string source, string fileName, string[] commandLineArguments) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { fileName }).ToArray()); int exitCode = csc.Run(outWriter); return exitCode; } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithNonExistingOutPath() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2012: Cannot open '" + dir.Path + "\\sub\\a.exe' for writing", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_01() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_02() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\ " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsDesktopOnly))] public void CompilationWithWrongOutPath_03() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:aaa:\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains(@"error CS2021: File name 'aaa:\a.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_04() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out: " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2005: Missing file specification for '/out:' option", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] public void EmittedSubsystemVersion() { var compilation = CSharpCompilation.Create("a.dll", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(subsystemVersion: SubsystemVersion.Create(5, 1)))); Assert.Equal(5, peHeaders.PEHeader.MajorSubsystemVersion); Assert.Equal(1, peHeaders.PEHeader.MinorSubsystemVersion); } [Fact] public void CreateCompilationWithKeyFile() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyfile:key.snk", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.IsType<DesktopStrongNameProvider>(comp.Options.StrongNameProvider); } [Fact] public void CreateCompilationWithKeyContainer() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keycontainer:bbb", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilationFallbackCommand() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyFile:key.snk", "/features:UseLegacyStrongNameProvider" }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilation_MainAndTargetIncompatibilities() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var compilation = CSharpCompilation.Create("a.dll", options: TestOptions.ReleaseDll); var options = compilation.Options; Assert.Equal(0, options.Errors.Length); options = options.WithMainTypeName("a"); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); var comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithOutputKind(OutputKind.WindowsApplication); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS1555: Could not find 'a' specified for Main method Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("a") ); options = options.WithOutputKind(OutputKind.NetModule); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithMainTypeName(null); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify(); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void SpecifyProperCodePage() { byte[] source = { 0x63, // c 0x6c, // l 0x61, // a 0x73, // s 0x73, // s 0x20, // 0xd0, 0x96, // Utf-8 Cyrillic character 0x7b, // { 0x7d, // } }; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllBytes(source); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:library \"{file}\"", startFolder: dir.Path); Assert.Equal("", output); // Autodetected UTF8, NO ERROR output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /preferreduilang:en /t:library /codepage:20127 \"{file}\"", expectedRetCode: 1, startFolder: dir.Path); // 20127: US-ASCII // 0xd0, 0x96 ==> ERROR Assert.Equal(@" a.cs(1,7): error CS1001: Identifier expected a.cs(1,7): error CS1514: { expected a.cs(1,7): error CS1513: } expected a.cs(1,7): error CS8803: Top-level statements must precede namespace and type declarations. a.cs(1,7): error CS1525: Invalid expression term '??' a.cs(1,9): error CS1525: Invalid expression term '{' a.cs(1,9): error CS1002: ; expected ".Trim(), Regex.Replace(output, "^.*a.cs", "a.cs", RegexOptions.Multiline).Trim()); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForDll() { var source = @" class C { } "; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForAppContainerExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsRuntimeApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinMD() { var source = @" class C { } "; CheckManifestString(source, OutputKind.WindowsRuntimeMetadata, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForModule() { var source = @" class C { } "; CheckManifestString(source, OutputKind.NetModule, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForExe() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var explicitManifestStream = new MemoryStream(Encoding.UTF8.GetBytes(explicitManifest)); var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest, expectedManifest); } // DLLs don't get the default manifest, but they do respect explicitly set manifests. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForDll() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest, expectedManifest); } // Modules don't have manifests, even if one is explicitly specified. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForModule() { var source = @" class C { } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; CheckManifestString(source, OutputKind.NetModule, explicitManifest, expectedManifest: null); } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeLibrary([In] IntPtr hFile); private void CheckManifestString(string source, OutputKind outputKind, string explicitManifest, string expectedManifest) { var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("Test.cs").WriteAllText(source); string outputFileName; string target; switch (outputKind) { case OutputKind.ConsoleApplication: outputFileName = "Test.exe"; target = "exe"; break; case OutputKind.WindowsApplication: outputFileName = "Test.exe"; target = "winexe"; break; case OutputKind.DynamicallyLinkedLibrary: outputFileName = "Test.dll"; target = "library"; break; case OutputKind.NetModule: outputFileName = "Test.netmodule"; target = "module"; break; case OutputKind.WindowsRuntimeMetadata: outputFileName = "Test.winmdobj"; target = "winmdobj"; break; case OutputKind.WindowsRuntimeApplication: outputFileName = "Test.exe"; target = "appcontainerexe"; break; default: throw TestExceptionUtilities.UnexpectedValue(outputKind); } MockCSharpCompiler csc; if (explicitManifest == null) { csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), Path.GetFileName(sourceFile.Path), }); } else { var manifestFile = dir.CreateFile("Test.config").WriteAllText(explicitManifest); csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), string.Format("/win32manifest:{0}", Path.GetFileName(manifestFile.Path)), Path.GetFileName(sourceFile.Path), }); } int actualExitCode = csc.Run(new StringWriter(CultureInfo.InvariantCulture)); Assert.Equal(0, actualExitCode); //Open as data IntPtr lib = LoadLibraryEx(Path.Combine(dir.Path, outputFileName), IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); const string resourceType = "#24"; var resourceId = outputKind == OutputKind.DynamicallyLinkedLibrary ? "#2" : "#1"; uint manifestSize; if (expectedManifest == null) { Assert.Throws<Win32Exception>(() => Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize)); } else { IntPtr manifestResourcePointer = Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize); string actualManifest = Win32Res.ManifestResourceToXml(manifestResourcePointer, manifestSize); Assert.Equal(expectedManifest, actualManifest); } FreeLibrary(lib); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_01() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { int x; // CS0168 } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /warnaserror ").Path; // Checks the base case without /noconfig (expect to see error) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/NOCONFIG", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "-noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_02() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_03() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /NOCONFIG ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_04() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" -noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact, WorkItem(530024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530024")] public void NoStdLib() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/nostdlib", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("{FILE}(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported", outWriter.ToString().Replace(Path.GetFileName(src.Path), "{FILE}").Trim()); // Bug#15021: breaking change - empty source no error with /nostdlib src.WriteAllText("namespace System { }"); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/langversion:8", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } private string GetDefaultResponseFilePath() { var cscRsp = global::TestResources.ResourceLoader.GetResourceBlob("csc.rsp"); return Temp.CreateFile().WriteAllBytes(cscRsp).Path; } [Fact, WorkItem(530359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530359")] public void NoStdLib02() { #region "source" var source = @" // <Title>A collection initializer can be declared with a user-defined IEnumerable that is declared in a user-defined System.Collections</Title> using System.Collections; class O<T> where T : new() { public T list = new T(); } class C { static StructCollection sc = new StructCollection { 1 }; public static int Main() { ClassCollection cc = new ClassCollection { 2 }; var o1 = new O<ClassCollection> { list = { 5 } }; var o2 = new O<StructCollection> { list = sc }; return 0; } } struct StructCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } class ClassCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } namespace System.Collections { public interface IEnumerable { void Add(int t); } } "; #endregion #region "mslib" var mslib = @" namespace System { public class Object {} public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct SByte { } public struct UInt32 { } public struct UInt64 { } public struct Char { } public struct Boolean { } public struct UInt16 { } public struct UIntPtr { } public struct IntPtr { } public class Delegate { } public class String { public int Length { get { return 10; } } } public class MulticastDelegate { } public class Array { } public class Exception { public Exception(string s){} } public class Type { } public class ValueType { } public class Enum { } public interface IEnumerable { } public interface IDisposable { } public class Attribute { } public class ParamArrayAttribute { } public struct Void { } public struct RuntimeFieldHandle { } public struct RuntimeTypeHandle { } public class Activator { public static T CreateInstance<T>(){return default(T);} } namespace Collections { public interface IEnumerator { } } namespace Runtime { namespace InteropServices { public class OutAttribute { } } namespace CompilerServices { public class RuntimeHelpers { } } } namespace Reflection { public class DefaultMemberAttribute { } } } "; #endregion var src = Temp.CreateFile("NoStdLib02.cs"); src.WriteAllText(source + mslib); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); string OriginalSource = src.Path; src = Temp.CreateFile("NoStdLib02b.cs"); src.WriteAllText(mslib); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(OriginalSource); CleanupAllGeneratedFiles(src.Path); } [Fact, WorkItem(546018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546018"), WorkItem(546020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546020"), WorkItem(546024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546024"), WorkItem(546049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546049")] public void InvalidDefineSwitch() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", src.ToString(), "/define" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:""""" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define: " }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,,," }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,blah,Blah" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a;;b@" }).Run(outWriter); Assert.Equal(0, exitCode); var errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", errorLines[0]); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", errorLines[1]); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a,b@;" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", outWriter.ToString().Trim()); //Bug 531612 - Native would normally not give the 2nd warning outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1", @"/d:TRACE=TRUE,DEBUG=TRUE" }).Run(outWriter); Assert.Equal(0, exitCode); errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1' is not a valid identifier", errorLines[0]); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'TRACE=TRUE' is not a valid identifier", errorLines[1]); CleanupAllGeneratedFiles(src.Path); } [WorkItem(733242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/733242")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug733242() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); using (var xmlFileHandle = File.Open(xml.ToString(), FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite)) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))); using (var reader = new StreamReader(xmlFileHandle)) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [WorkItem(768605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768605")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug768605() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC</summary> class C {} /// <summary>XYZ</summary> class E {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> <member name=""T:E""> <summary>XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } src.WriteAllText( @" /// <summary>ABC</summary> class C {} "); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> </members> </doc>".Trim(), content.Trim()); } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [Fact] public void ParseFullpaths() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths" }, WorkingDirectory); Assert.True(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); } [Fact] public void CheckFullpaths() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public static void Main() { string x; } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); // Checks the base case without /fullpaths (expect to see relative path name) // c:\temp> csc.exe c:\temp\a.cs // a.cs(6,16): warning CS0168: The variable 'x' is declared but never used var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see relative path name) // c:\temp> csc.exe c:\temp\example\a.cs // example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); Assert.DoesNotContain(source, outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /fullpaths (expect to see the full paths) // c:\temp> csc.exe c:\temp\a.cs /fullpaths // c:\temp\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/fullpaths", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + @"(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see the full path name) // c:\temp> csc.exe c:\temp\example\a.cs /fullpaths // c:\temp\example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs /fullpaths // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(source)), Path.GetFileName(source))); } [Fact] public void DefaultResponseFile() { var sdkDirectory = SdkDirectory; MockCSharpCompiler csc = new MockCSharpCompiler( GetDefaultResponseFilePath(), RuntimeUtilities.CreateBuildPaths(WorkingDirectory, sdkDirectory), new string[0]); AssertEx.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, "Accessibility.dll", "Microsoft.CSharp.dll", "System.Configuration.dll", "System.Configuration.Install.dll", "System.Core.dll", "System.Data.dll", "System.Data.DataSetExtensions.dll", "System.Data.Linq.dll", "System.Data.OracleClient.dll", "System.Deployment.dll", "System.Design.dll", "System.DirectoryServices.dll", "System.dll", "System.Drawing.Design.dll", "System.Drawing.dll", "System.EnterpriseServices.dll", "System.Management.dll", "System.Messaging.dll", "System.Runtime.Remoting.dll", "System.Runtime.Serialization.dll", "System.Runtime.Serialization.Formatters.Soap.dll", "System.Security.dll", "System.ServiceModel.dll", "System.ServiceModel.Web.dll", "System.ServiceProcess.dll", "System.Transactions.dll", "System.Web.dll", "System.Web.Extensions.Design.dll", "System.Web.Extensions.dll", "System.Web.Mobile.dll", "System.Web.RegularExpressions.dll", "System.Web.Services.dll", "System.Windows.Forms.dll", "System.Workflow.Activities.dll", "System.Workflow.ComponentModel.dll", "System.Workflow.Runtime.dll", "System.Xml.dll", "System.Xml.Linq.dll", }, StringComparer.OrdinalIgnoreCase); } [Fact] public void DefaultResponseFileNoConfig() { MockCSharpCompiler csc = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/noconfig" }); Assert.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, }, StringComparer.OrdinalIgnoreCase); } [Fact, WorkItem(545954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545954")] public void TestFilterParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" #pragma warning disable 440 using global = A; // CS0440 class A { static void Main() { #pragma warning suppress 440 } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(Path.GetFileName(source) + "(7,17): warning CS1634: Expected 'disable' or 'restore'", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/nowarn:1634", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", Path.Combine(baseDir, "nonexistent.cs"), source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2001: Source file '" + Path.Combine(baseDir, "nonexistent.cs") + "' could not be found.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546058")] public void TestNoWarnParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Test { static void Main() { //Generates warning CS1522: Empty switch block switch (1) { } //Generates warning CS0642: Possible mistaken empty statement while (false) ; { } } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1522,642", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(41610, "https://github.com/dotnet/roslyn/issues/41610")] public void TestWarnAsError_CS8632() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public string? field; public static void Main() { } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror:nullable", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(4,18): error CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546076")] public void TestWarnAsError_CS1522() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class Test { // CS0169 (level 3) private int x; // CS0109 (level 4) public new void Method() { } public static int Main() { int i = 5; // CS1522 (level 1) switch (i) { } return 0; // CS0162 (level 2) i = 6; } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(12,20): error CS1522: Empty switch block {fileName}(15,9): error CS0162: Unreachable code detected {fileName}(5,17): error CS0169: The field 'Test.x' is never used", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact(), WorkItem(546025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546025")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_01() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(TestResources.DiagnosticTests.badresfile).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Image is too small.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact(), WorkItem(217718, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=217718")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_02() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(new byte[] { 0, 0 }).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Unrecognized resource file format.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact, WorkItem(546114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546114")] public void TestFilterCommandLineDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class A { static void Main() { } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", "/out:goo.dll", "/nowarn:2008" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); System.IO.File.Delete(System.IO.Path.Combine(baseDir, "goo.dll")); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_Bug15905() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Program { #pragma warning disable 1998 public static void Main() { } #pragma warning restore 1998 } ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // Repro case 1 int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); // Repro case 2 exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1998", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ExistingPdb() { var dir = Temp.CreateDirectory(); var source1 = dir.CreateFile("program1.cs").WriteAllText(@" class " + new string('a', 10000) + @" { public static void Main() { } }"); var source2 = dir.CreateFile("program2.cs").WriteAllText(@" class Program2 { public static void Main() { } }"); var source3 = dir.CreateFile("program3.cs").WriteAllText(@" class Program3 { public static void Main() { } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int oldSize = 16 * 1024; var exe = dir.CreateFile("Program.exe"); using (var stream = File.OpenWrite(exe.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } var pdb = dir.CreateFile("Program.pdb"); using (var stream = File.OpenWrite(pdb.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } int exitCode1 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source1.Path }).Run(outWriter); Assert.NotEqual(0, exitCode1); ValidateZeroes(exe.Path, oldSize); ValidateZeroes(pdb.Path, oldSize); int exitCode2 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source2.Path }).Run(outWriter); Assert.Equal(0, exitCode2); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } Assert.True(new FileInfo(exe.Path).Length < oldSize); Assert.True(new FileInfo(pdb.Path).Length < oldSize); int exitCode3 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source3.Path }).Run(outWriter); Assert.Equal(0, exitCode3); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } } private static void ValidateZeroes(string path, int count) { using (var stream = File.OpenRead(path)) { byte[] buffer = new byte[count]; stream.Read(buffer, 0, buffer.Length); for (int i = 0; i < buffer.Length; i++) { if (buffer[i] != 0) { Assert.True(false); } } } } /// <summary> /// When the output file is open with <see cref="FileShare.Read"/> | <see cref="FileShare.Delete"/> /// the compiler should delete the file to unblock build while allowing the reader to continue /// reading the previous snapshot of the file content. /// /// On Windows we can read the original data directly from the stream without creating a memory map. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void FileShareDeleteCompatibility_Windows() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); var libPdb = dir.CreateFile("Lib.pdb").WriteAllText("PDB"); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/debug:full", libSrc.Path }).Run(outWriter); if (exitCode != 0) { AssertEx.AssertEqualToleratingWhitespaceDifferences("", outWriter.ToString()); } Assert.Equal(0, exitCode); AssertEx.Equal(new byte[] { 0x4D, 0x5A }, ReadBytes(libDll.Path, 2)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); AssertEx.Equal(new byte[] { 0x4D, 0x69 }, ReadBytes(libPdb.Path, 2)); AssertEx.Equal(new[] { (byte)'P', (byte)'D', (byte)'B' }, ReadBytes(fsPdb, 3)); fsDll.Dispose(); fsPdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } /// <summary> /// On Linux/Mac <see cref="FileShare.Delete"/> on its own doesn't do anything. /// We need to create the actual memory map. This works on Windows as well. /// </summary> [WorkItem(8896, "https://github.com/dotnet/roslyn/issues/8896")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void FileShareDeleteCompatibility_Xplat() { var bytes = TestResources.MetadataTests.InterfaceAndClass.CSClasses01; var mvid = ReadMvid(new MemoryStream(bytes)); var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllBytes(bytes); var libPdb = dir.CreateFile("Lib.pdb").WriteAllBytes(bytes); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var peDll = new PEReader(fsDll); var pePdb = new PEReader(fsPdb); // creates memory map view: var imageDll = peDll.GetEntireImage(); var imagePdb = pePdb.GetEntireImage(); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/target:library /debug:portable \"{libSrc.Path}\"", startFolder: dir.ToString()); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" Microsoft (R) Visual C# Compiler version {s_compilerVersion} Copyright (C) Microsoft Corporation. All rights reserved.", output); // reading original content from the memory map: Assert.Equal(mvid, ReadMvid(new MemoryStream(imageDll.GetContent().ToArray()))); Assert.Equal(mvid, ReadMvid(new MemoryStream(imagePdb.GetContent().ToArray()))); // reading original content directly from the streams: fsDll.Position = 0; fsPdb.Position = 0; Assert.Equal(mvid, ReadMvid(fsDll)); Assert.Equal(mvid, ReadMvid(fsPdb)); // reading new content from the file: using (var fsNewDll = File.OpenRead(libDll.Path)) { Assert.NotEqual(mvid, ReadMvid(fsNewDll)); } // Portable PDB metadata signature: AssertEx.Equal(new[] { (byte)'B', (byte)'S', (byte)'J', (byte)'B' }, ReadBytes(libPdb.Path, 4)); // dispose PEReaders (they dispose the underlying file streams) peDll.Dispose(); pePdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); // files can be deleted now: File.Delete(libSrc.Path); File.Delete(libDll.Path); File.Delete(libPdb.Path); // directory can be deleted (should be empty): Directory.Delete(dir.Path, recursive: false); } private static Guid ReadMvid(Stream stream) { using (var peReader = new PEReader(stream, PEStreamOptions.LeaveOpen)) { var mdReader = peReader.GetMetadataReader(); return mdReader.GetGuid(mdReader.GetModuleDefinition().Mvid); } } // Seems like File.SetAttributes(libDll.Path, FileAttributes.ReadOnly) doesn't restrict access to the file on Mac (Linux passes). [ConditionalFact(typeof(WindowsOnly)), WorkItem(8939, "https://github.com/dotnet/roslyn/issues/8939")] public void FileShareDeleteCompatibility_ReadOnlyFiles() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); File.SetAttributes(libDll.Path, FileAttributes.ReadOnly); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(libDll.Path, 3)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); fsDll.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } [Fact] public void FileShareDeleteCompatibility_ExistingDirectory() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateDirectory("Lib.dll"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); } private byte[] ReadBytes(Stream stream, int count) { var buffer = new byte[count]; stream.Read(buffer, 0, count); return buffer; } private byte[] ReadBytes(string path, int count) { using (var stream = File.OpenRead(path)) { return ReadBytes(stream, count); } } [Fact] public void IOFailure_DisposeOutputFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{exePath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposePdbFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var pdbPath = Path.ChangeExtension(exePath, "pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{pdbPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposeXmlFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var xmlPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/doc:{xmlPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{xmlPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Theory] [InlineData("portable")] [InlineData("full")] public void IOFailure_DisposeSourceLinkFile(string format) { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var sourceLinkPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.json"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug:" + format, $"/sourcelink:{sourceLinkPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == sourceLinkPath) { return new TestStream(backingStream: new MemoryStream(Encoding.UTF8.GetBytes(@" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } ")), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{sourceLinkPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_OpenOutputFile() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { throw new IOException(); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS2012: Cannot open '{exePath}' for writing", outWriter.ToString()); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenPdbFileNotCalled() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); string pdbPath = Path.ChangeExtension(exePath, ".pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/debug-", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { throw new IOException(); } return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(0, csc.Run(outWriter)); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); System.IO.File.Delete(pdbPath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenXmlFinal() { string sourcePath = MakeTrivialExe(); string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/doc:" + xmlPath, sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { throw new IOException(); } else { return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); } }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); var expectedOutput = string.Format("error CS0016: Could not write to output file '{0}' -- 'I/O error occurred.'", xmlPath); Assert.Equal(expectedOutput, outWriter.ToString().Trim()); Assert.NotEqual(0, exitCode); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); } private string MakeTrivialExe(string directory = null) { return Temp.CreateFile(directory: directory, prefix: "", extension: ".cs").WriteAllText(@" class Program { public static void Main() { } } ").Path; } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_AllErrorCodes() { const int jump = 200; for (int i = 0; i < 8000; i += (8000 / jump)) { int startErrorCode = (int)i * jump; int endErrorCode = startErrorCode + jump; string source = ComputeSourceText(startErrorCode, endErrorCode); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in a #pragma directive // (or via /nowarn /warnaserror flags on the command line). // Going forward, we won't generate any warning in such cases. This will make // maintenance of backwards compatibility easier (we no longer need to worry // about breaking existing projects / command lines if we deprecate / remove // an old warning code). Test(source, startErrorCode, endErrorCode); } } private static string ComputeSourceText(int startErrorCode, int endErrorCode) { string pragmaDisableWarnings = String.Empty; for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { string pragmaDisableStr = @"#pragma warning disable " + errorCode.ToString() + @" "; pragmaDisableWarnings += pragmaDisableStr; } return pragmaDisableWarnings + @" public class C { public static void Main() { } }"; } private void Test(string source, int startErrorCode, int endErrorCode) { string sourcePath = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(source).Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", sourcePath }).Run(outWriter); Assert.Equal(0, exitCode); var cscOutput = outWriter.ToString().Trim(); for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { Assert.True(cscOutput == string.Empty, "Failed at error code: " + errorCode); } CleanupAllGeneratedFiles(sourcePath); } [Fact] public void WriteXml() { var source = @" /// <summary> /// A subtype of <see cref=""object""/>. /// </summary> public class C { } "; var sourcePath = Temp.CreateFile(directory: WorkingDirectory, extension: ".cs").WriteAllText(source).Path; string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/target:library", "/out:Test.dll", "/doc:" + xmlPath, sourcePath }); var writer = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(writer); if (exitCode != 0) { Console.WriteLine(writer.ToString()); Assert.Equal(0, exitCode); } var bytes = File.ReadAllBytes(xmlPath); var actual = new string(Encoding.UTF8.GetChars(bytes)); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> A subtype of <see cref=""T:System.Object""/>. </summary> </member> </members> </doc> "; Assert.Equal(expected.Trim(), actual.Trim()); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); CleanupAllGeneratedFiles(xmlPath); } [WorkItem(546468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546468")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void CS2002WRN_FileAlreadyIncluded() { const string cs2002 = @"warning CS2002: Source file '{0}' specified multiple times"; TempDirectory tempParentDir = Temp.CreateDirectory(); TempDirectory tempDir = tempParentDir.CreateDirectory("tmpDir"); TempFile tempFile = tempDir.CreateFile("a.cs").WriteAllText(@"public class A { }"); // Simple case var commandLineArgs = new[] { "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times string aWrnString = String.Format(cs2002, "a.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, aWrnString); // Multiple duplicates commandLineArgs = new[] { "a.cs", "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times var warnings = new[] { aWrnString }; TestCS2002(commandLineArgs, tempDir.Path, 0, warnings); // Case-insensitive commandLineArgs = new[] { "a.cs", "A.cs" }; // warning CS2002: Source file 'A.cs' specified multiple times string AWrnString = String.Format(cs2002, "A.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, AWrnString); // Different extensions tempDir.CreateFile("a.csx"); commandLineArgs = new[] { "a.cs", "a.csx" }; // No errors or warnings TestCS2002(commandLineArgs, tempDir.Path, 0, String.Empty); // Absolute vs Relative commandLineArgs = new[] { @"tmpDir\a.cs", tempFile.Path }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times string tmpDiraString = String.Format(cs2002, @"tmpDir\a.cs"); TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Both relative commandLineArgs = new[] { @"tmpDir\..\tmpDir\a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // With wild cards commandLineArgs = new[] { tempFile.Path, @"tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // "/recurse" scenarios commandLineArgs = new[] { @"/recurse:a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); commandLineArgs = new[] { @"/recurse:a.cs", @"/recurse:tmpDir\..\tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Invalid file/path characters const string cs1504 = @"error CS1504: Source file '{0}' could not be opened -- {1}"; commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, "tmpDir\a.cs" }; // error CS1504: Source file '{0}' could not be opened: Illegal characters in path. var formattedcs1504Str = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, "tmpDir\a.cs"), "Illegal characters in path."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504Str); commandLineArgs = new[] { tempFile.Path, @"tmpDi\r*a?.cs" }; var parseDiags = new[] { // error CS2021: File name 'tmpDi\r*a?.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"tmpDi\r*a?.cs"), // error CS2001: Source file 'tmpDi\r*a?.cs' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments(@"tmpDi\r*a?.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); char currentDrive = Directory.GetCurrentDirectory()[0]; commandLineArgs = new[] { tempFile.Path, currentDrive + @":a.cs" }; parseDiags = new[] { // error CS2021: File name 'e:a.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + @":a.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, @":a.cs" }; // error CS1504: Source file '{0}' could not be opened: {1} var formattedcs1504 = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, @":a.cs"), @"The given path's format is not supported."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504); CleanupAllGeneratedFiles(tempFile.Path); System.IO.Directory.Delete(tempParentDir.Path, true); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string compileDiagnostic, params DiagnosticDescription[] parseDiagnostics) { TestCS2002(commandLineArgs, baseDirectory, expectedExitCode, new[] { compileDiagnostic }, parseDiagnostics); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string[] compileDiagnostics, params DiagnosticDescription[] parseDiagnostics) { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var allCommandLineArgs = new[] { "/nologo", "/preferreduilang:en", "/t:library" }.Concat(commandLineArgs).ToArray(); // Verify command line parser diagnostics. DefaultParse(allCommandLineArgs, baseDirectory).Errors.Verify(parseDiagnostics); // Verify compile. int exitCode = CreateCSharpCompiler(null, baseDirectory, allCommandLineArgs).Run(outWriter); Assert.Equal(expectedExitCode, exitCode); if (parseDiagnostics.IsEmpty()) { // Verify compile diagnostics. string outString = String.Empty; for (int i = 0; i < compileDiagnostics.Length; i++) { if (i != 0) { outString += @" "; } outString += compileDiagnostics[i]; } Assert.Equal(outString, outWriter.ToString().Trim()); } else { Assert.Null(compileDiagnostics); } } [Fact] public void ErrorLineEnd() { var tree = SyntaxFactory.ParseSyntaxTree("class C public { }", path: "goo"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/errorendlocation" }); var loc = new SourceLocation(tree.GetCompilationUnitRoot().FindToken(6)); var diag = new CSDiagnostic(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_MetadataNameTooLong), loc); var text = comp.DiagnosticFormatter.Format(diag); string stringStart = "goo(1,7,1,8)"; Assert.Equal(stringStart, text.Substring(0, stringStart.Length)); } [Fact] public void ReportAnalyzer() { var parsedArgs1 = DefaultParse(new[] { "a.cs", "/reportanalyzer" }, WorkingDirectory); Assert.True(parsedArgs1.ReportAnalyzer); var parsedArgs2 = DefaultParse(new[] { "a.cs", "" }, WorkingDirectory); Assert.False(parsedArgs2.ReportAnalyzer); } [Fact] public void ReportAnalyzerOutput() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains("WarningDiagnosticAnalyzer (Warning01)", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersParse() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/SKIPANALYZERS+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersSemantics(bool skipAnalyzers) { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var skipAnalyzersFlag = "/skipanalyzers" + (skipAnalyzers ? "+" : "-"); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { skipAnalyzersFlag, "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (skipAnalyzers) { Assert.DoesNotContain(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.DoesNotContain(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } else { Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(24835, "https://github.com/dotnet/roslyn/issues/24835")] public void TestCompilationSuccessIfOnlySuppressedDiagnostics() { var srcFile = Temp.CreateFile().WriteAllText(@" #pragma warning disable Warning01 class C { } "); var errorLog = Temp.CreateFile(); var csc = CreateCSharpCompiler( null, workingDirectory: Path.GetDirectoryName(srcFile.Path), args: new[] { "/errorlog:" + errorLog.Path, "/warnaserror+", "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new WarningDiagnosticAnalyzer())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); // Previously, the compiler would return error code 1 without printing any diagnostics Assert.Empty(outWriter.ToString()); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(errorLog.Path); } [Fact] [WorkItem(1759, "https://github.com/dotnet/roslyn/issues/1759")] public void AnalyzerDiagnosticThrowsInGetMessage() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerThatThrowsInGetMessage is reported, though it doesn't have the message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(3707, "https://github.com/dotnet/roslyn/issues/3707")] public void AnalyzerExceptionDiagnosticCanBeConfigured() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", $"/warnaserror:{AnalyzerExecutor.AnalyzerExceptionDiagnosticId}", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); var output = outWriter.ToString(); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(4589, "https://github.com/dotnet/roslyn/issues/4589")] public void AnalyzerReportsMisformattedDiagnostic() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerReportingMisformattedDiagnostic())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerReportingMisformattedDiagnostic is reported with the message format string, instead of the formatted message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.MessageFormat.ToString(CultureInfo.InvariantCulture), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void ErrorPathsFromLineDirectives() { string sampleProgram = @" #line 10 "".."" //relative path using System* "; var syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new string[] { }); var text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); //Pull off the last segment of the current directory. var expectedPath = Path.GetDirectoryName(WorkingDirectory); //the end of the diagnostic's "file" portion should be signaled with the '(' of the line/col info. Assert.Equal('(', text[expectedPath.Length]); sampleProgram = @" #line 10 "".>"" //invalid path character using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith(".>", StringComparison.Ordinal)); sampleProgram = @" #line 10 ""http://goo.bar/baz.aspx"" //URI using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith("http://goo.bar/baz.aspx", StringComparison.Ordinal)); } [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [Fact] public void PreferredUILang() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-US" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de-AT" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(531263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531263")] [Fact] public void EmptyFileName() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "" }).Run(outWriter); Assert.NotEqual(0, exitCode); // error CS2021: File name '' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Assert.Contains("CS2021", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void NoInfoDiagnostics() { string filePath = Temp.CreateFile().WriteAllText(@" using System.Diagnostics; // Unused. ").Path; var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(filePath); } [Fact] public void RuntimeMetadataVersion() { var parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:v4.0.30319" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("v4.0.30319", parsedArgs.EmitOptions.RuntimeMetadataVersion); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:-_+@%#*^" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("-_+@%#*^", parsedArgs.EmitOptions.RuntimeMetadataVersion); var comp = CreateEmptyCompilation(string.Empty); Assert.Equal("v4.0.30319", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "v4.0.30319"))).Module.MetadataVersion); comp = CreateEmptyCompilation(string.Empty); Assert.Equal("_+@%#*^", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "_+@%#*^"))).Module.MetadataVersion); } [WorkItem(715339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715339")] [ConditionalFact(typeof(WindowsOnly))] public void WRN_InvalidSearchPathDir() { var baseDir = Temp.CreateDirectory(); var sourceFile = baseDir.CreateFile("Source.cs"); var invalidPath = "::"; var nonExistentPath = "DoesNotExist"; // lib switch DefaultParse(new[] { "/lib:" + invalidPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path '::' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "/LIB option", "path is too long or invalid")); DefaultParse(new[] { "/lib:" + nonExistentPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "/LIB option", "directory does not exist")); // LIB environment variable DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: invalidPath).Errors.Verify( // warning CS1668: Invalid search path '::' specified in 'LIB environment variable' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "LIB environment variable", "path is too long or invalid")); DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: nonExistentPath).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in 'LIB environment variable' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "LIB environment variable", "directory does not exist")); CleanupAllGeneratedFiles(sourceFile.Path); } [WorkItem(650083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650083")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/55730")] public void ReservedDeviceNameAsFileName() { var parsedArgs = DefaultParse(new[] { "com9.cs", "/t:library " }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); parsedArgs = DefaultParse(new[] { "a.cs", "/t:library ", "/appconfig:.\\aux.config" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/out:com1.dll " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/doc:..\\lpt2.xml: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/debug+", "/pdb:.\\prn.pdb" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "@con.rsp" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_OpenResponseFile, parsedArgs.Errors.First().Code); } [Fact] public void ReservedDeviceNameAsFileName2() { string filePath = Temp.CreateFile().WriteAllText(@"class C {}").Path; // make sure reserved device names don't var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/r:com2.dll", "/target:library", "/preferreduilang:en", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file 'com2.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/link:..\\lpt8.dll", "/target:library", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file '..\\lpt8.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/lib:aux", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("warning CS1668: Invalid search path 'aux' specified in '/LIB option' -- 'directory does not exist'", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); } [Fact] public void ParseFeatures() { var args = DefaultParse(new[] { "/features:Test", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal("Test", args.ParseOptions.Features.Single().Key); args = DefaultParse(new[] { "/features:Test", "a.vb", "/Features:Experiment" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.ParseOptions.Features.Count); Assert.True(args.ParseOptions.Features.ContainsKey("Test")); Assert.True(args.ParseOptions.Features.ContainsKey("Experiment")); args = DefaultParse(new[] { "/features:Test=false,Key=value", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "false" }, { "Key", "value" } })); args = DefaultParse(new[] { "/features:Test,", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "true" } })); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseAdditionalFile() { var args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles.Single().Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:app.manifest" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:web.config" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:..\\web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\web.config"), args.AdditionalFiles.Single().Path); var baseDir = Temp.CreateDirectory(); baseDir.CreateFile("web1.config"); baseDir.CreateFile("web2.config"); baseDir.CreateFile("web3.config"); args = DefaultParse(new[] { "/additionalfile:web*.config", "a.cs" }, baseDir.Path); args.Errors.Verify(); Assert.Equal(3, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(baseDir.Path, "web1.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(baseDir.Path, "web2.config"), args.AdditionalFiles[1].Path); Assert.Equal(Path.Combine(baseDir.Path, "web3.config"), args.AdditionalFiles[2].Path); args = DefaultParse(new[] { "/additionalfile:web.config;app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { @"/additionalfile:""web.config,app.manifest""", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config,app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile:web.config:app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config:app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); args = DefaultParse(new[] { "/additionalfile:", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); } [Fact] public void ParseEditorConfig() { var args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:subdir\\.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:..\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\.editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig;subdir\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); args = DefaultParse(new[] { "/analyzerconfig:", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); } [Fact] public void NullablePublicOnly() { string source = @"namespace System.Runtime.CompilerServices { public sealed class NullableAttribute : Attribute { } // missing constructor } public class Program { private object? F = null; }"; string errorMessage = "error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'"; string filePath = Temp.CreateFile().WriteAllText(source).Path; int exitCode; string output; // No /feature (exitCode, output) = compileAndRun(featureOpt: null); Assert.Equal(1, exitCode); Assert.Contains(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly (exitCode, output) = compileAndRun("/features:nullablePublicOnly"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=true (exitCode, output) = compileAndRun("/features:nullablePublicOnly=true"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=false (the value is ignored) (exitCode, output) = compileAndRun("/features:nullablePublicOnly=false"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); (int, string) compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/langversion:8", "/nullable+", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return (exitCode, outWriter.ToString()); }; } // See also NullableContextTests.NullableAnalysisFlags_01(). [Fact] public void NullableAnalysisFlags() { string source = @"class Program { #nullable enable static object F1() => null; #nullable disable static object F2() => null; }"; string filePath = Temp.CreateFile().WriteAllText(source).Path; string fileName = Path.GetFileName(filePath); string[] expectedWarningsAll = new[] { fileName + "(4,27): warning CS8603: Possible null reference return." }; string[] expectedWarningsNone = Array.Empty<string>(); AssertEx.Equal(expectedWarningsAll, compileAndRun(featureOpt: null)); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=always")); AssertEx.Equal(expectedWarningsNone, compileAndRun("/features:run-nullable-analysis=never")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=ALWAYS")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=NEVER")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=true")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=false")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=unknown")); // unrecognized value ignored CleanupAllGeneratedFiles(filePath); string[] compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/nologo", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return outWriter.ToString().Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); }; } private static int OccurrenceCount(string source, string word) { var n = 0; var index = source.IndexOf(word, StringComparison.Ordinal); while (index >= 0) { ++n; index = source.IndexOf(word, index + word.Length, StringComparison.Ordinal); } return n; } private string VerifyOutput(TempDirectory sourceDir, TempFile sourceFile, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, int? expectedExitCode = null, bool errorlog = false, IEnumerable<ISourceGenerator> generators = null, params DiagnosticAnalyzer[] analyzers) { var args = new[] { "/nologo", "/preferreduilang:en", "/t:library", sourceFile.Path }; if (includeCurrentAssemblyAsAnalyzerReference) { args = args.Append("/a:" + Assembly.GetExecutingAssembly().Location); } if (errorlog) { args = args.Append("/errorlog:errorlog"); } if (additionalFlags != null) { args = args.Append(additionalFlags); } var csc = CreateCSharpCompiler(null, sourceDir.Path, args, analyzers: analyzers.ToImmutableArrayOrEmpty(), generators: generators.ToImmutableArrayOrEmpty()); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); var output = outWriter.ToString(); expectedExitCode ??= expectedErrorCount > 0 ? 1 : 0; Assert.True( expectedExitCode == exitCode, string.Format("Expected exit code to be '{0}' was '{1}'.{2} Output:{3}{4}", expectedExitCode, exitCode, Environment.NewLine, Environment.NewLine, output)); Assert.DoesNotContain("hidden", output, StringComparison.Ordinal); if (expectedInfoCount == 0) { Assert.DoesNotContain("info", output, StringComparison.Ordinal); } else { // Info diagnostics are only logged with /errorlog. Assert.True(errorlog); Assert.Equal(expectedInfoCount, OccurrenceCount(output, "info")); } if (expectedWarningCount == 0) { Assert.DoesNotContain("warning", output, StringComparison.Ordinal); } else { Assert.Equal(expectedWarningCount, OccurrenceCount(output, "warning")); } if (expectedErrorCount == 0) { Assert.DoesNotContain("error", output, StringComparison.Ordinal); } else { Assert.Equal(expectedErrorCount, OccurrenceCount(output, "error")); } return output; } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [Fact] public void NoWarnAndWarnAsError_AnalyzerDriverWarnings() { // This assembly has an abstract MockAbstractDiagnosticAnalyzer type which should cause // compiler warning CS8032 to be produced when compilations created in this test try to load it. string source = @"using System;"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:CS8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be promoted to an error via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:8032" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_HiddenDiagnostic() { // This assembly has a HiddenDiagnosticAnalyzer type which should produce custom hidden // diagnostics for #region directives present in the compilations created in this test. var source = @"using System; #region Region #endregion"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /nowarn: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror+ has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warnaserror- has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror: promotes custom hidden diagnostic Hidden01 to an error. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror-: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Hidden01" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Hidden01", "/nowarn:8032" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Hidden01", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void NoWarnAndWarnAsError_InfoDiagnostic(bool errorlog) { // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. // This assembly has an InfoDiagnosticAnalyzer type which should produce custom info // diagnostics for the #pragma warning restore directives present in the compilations created in this test. var source = @"using System; #pragma warning restore"; var name = "a.cs"; string output; output = GetOutput(name, source, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 suppresses custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0" }, errorlog: errorlog); // TEST: Verify that custom info diagnostic Info01 can be individually suppressed via /nowarn:. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can never be promoted to an error via /warnaserror+. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when /warnaserror- is used. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can be individually promoted to an error via /warnaserror:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when passed to /warnaserror-:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0", "/warnaserror:Info01" }, errorlog: errorlog); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/warn:0" }); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Info01", "/nowarn:8032" }, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Info01", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); } private string GetOutput( string name, string source, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, bool errorlog = false) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(name); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference, additionalFlags, expectedInfoCount, expectedWarningCount, expectedErrorCount, null, errorlog); CleanupAllGeneratedFiles(file.Path); return output; } [WorkItem(11368, "https://github.com/dotnet/roslyn/issues/11368")] [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(998069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998069")] [WorkItem(998724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998724")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_WarningDiagnostic() { // This assembly has a WarningDiagnosticAnalyzer type which should produce custom warning // diagnostics for source types present in the compilations created in this test. string source = @" class C { static void Main() { int i; } } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 3); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:cs0168,warning01,700000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror- keeps compiler warning CS0168 as well as custom warning diagnostic Warning01 as warnings. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 can be individually promoted to an error via /warnaserror+:. // This doesn't work correctly currently - promoting compiler warning CS0168 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069). output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:CS0168" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:cs0168,warning01,58000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 as well as compiler warning CS0168 can be promoted to errors via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:CS0168,Warning01" }, expectedWarningCount: 1, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror+" }); // TEST: Verify that /warn:0 overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror-" }); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror-:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror+" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror-" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Something,CS0168,Warning01" }); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Warning01", "/warnaserror-:Warning01" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,CS0168,58000,8032", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-:Warning01,CS0168,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,CS0168,58000", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror+:Warning01,CS0168,58000" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Warning01,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_ErrorDiagnostic() { // This assembly has an ErrorDiagnosticAnalyzer type which should produce custom error // diagnostics for #pragma warning disable directives present in the compilations created in this test. string source = @"using System; #pragma warning disable"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:Error01" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror+:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when custom error diagnostic Error01 is present. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes custom error diagnostic Error01 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_CompilerErrorDiagnostic() { string source = @"using System; class C { static void Main() { int i = new Exception(); } }"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /nowarn:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when compiler error CS0029 is present. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes compiler error CS0029 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror:0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins1() { var arguments = DefaultParse(new[] { "/warnaserror-:3001", "/warnaserror" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(true)); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins2() { var arguments = DefaultParse(new[] { "/warnaserror", "/warnaserror-:3001" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(false)); } [WorkItem(1091972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091972")] [WorkItem(444, "CodePlex")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug1091972() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C { static void Main() { var textStreamReader = new System.IO.StreamReader(typeof(C).Assembly.GetManifestResourceStream(""doc.xml"")); System.Console.WriteLine(textStreamReader.ReadToEnd()); } } "); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /doc:doc.xml /out:out.exe /resource:doc.xml \"{0}\"", src.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml"))); var expected = @"<?xml version=""1.0""?> <doc> <assembly> <name>out</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(); using (var reader = new StreamReader(Path.Combine(dir.ToString(), "doc.xml"))) { var content = reader.ReadToEnd(); Assert.Equal(expected, content.Trim()); } output = ProcessUtilities.RunAndGetOutput(Path.Combine(dir.ToString(), "out.exe"), startFolder: dir.ToString()); Assert.Equal(expected, output.Trim()); CleanupAllGeneratedFiles(src.Path); } [ConditionalFact(typeof(WindowsOnly))] public void CommandLineMisc() { CSharpCommandLineArguments args = null; string baseDirectory = @"c:\test"; Func<string, CSharpCommandLineArguments> parse = (x) => FullParse(x, baseDirectory); args = parse(@"/out:""a.exe"""); Assert.Equal(@"a.exe", args.OutputFileName); args = parse(@"/pdb:""a.pdb"""); Assert.Equal(Path.Combine(baseDirectory, @"a.pdb"), args.PdbPath); // The \ here causes " to be treated as a quote, not as an escaping construct args = parse(@"a\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a""b", @"c:\test\c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"a\\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a\b c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"/nostdlib /r:""a.dll"",""b.dll"" c.cs"); Assert.Equal( new[] { @"a.dll", @"b.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a-s.dll"",""b-s.dll"" c.cs"); Assert.Equal( new[] { @"a-s.dll", @"b-s.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a,;s.dll"",""b,;s.dll"" c.cs"); Assert.Equal( new[] { @"a,;s.dll", @"b,;s.dll" }, args.MetadataReferences.Select(x => x.Reference)); } [Fact] public void CommandLine_ScriptRunner1() { var args = ScriptParse(new[] { "--", "script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "@script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "@script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "-script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "-script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "--", "--" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "--") }, args.SourceFiles.Select(f => f.Path)); Assert.True(args.SourceFiles[0].IsScript); AssertEx.Equal(new[] { "--" }, args.ScriptArguments); // TODO: fails on Linux (https://github.com/dotnet/roslyn/issues/5904) // Result: C:\/script.csx //args = ScriptParse(new[] { "-i", "script.csx", "--", "--" }, baseDirectory: @"C:\"); //Assert.True(args.InteractiveMode); //AssertEx.Equal(new[] { @"C:\script.csx" }, args.SourceFiles.Select(f => f.Path)); //Assert.True(args.SourceFiles[0].IsScript); //AssertEx.Equal(new[] { "--" }, args.ScriptArguments); } [WorkItem(127403, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/127403")] [Fact] public void ParseSeparatedPaths_QuotedComma() { var paths = CSharpCommandLineParser.ParseSeparatedPaths(@"""a, b"""); Assert.Equal( new[] { @"a, b" }, paths); } [Fact] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapParser() { var s = PathUtilities.DirectorySeparatorStr; var parsedArgs = DefaultParse(new[] { "/pathmap:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { $"/pathmap:abc{s}=/", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("abc" + s, "/"), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1,K2=V2", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K2" + s, "V2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:,,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=,=v", "a.cs" }, WorkingDirectory); Assert.Equal(2, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[1].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=v=bad", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:=v", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:\"supporting spaces=is hard\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("supporting spaces" + s, "is hard" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1=V 1\",\"K 2=V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1\"=\"V 1\",\"K 2\"=\"V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"a ==,,b\"=\"1,,== 2\",\"x ==,,y\"=\"3 4\",", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("a =,b" + s, "1,= 2" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("x =,y" + s, "3 4" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { @"/pathmap:C:\temp\=/_1/,C:\temp\a\=/_2/,C:\temp\a\b\=/_3/", "a.cs", @"a\b.cs", @"a\b\c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\b\", "/_3/"), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\", "/_2/"), parsedArgs.PathMap[1]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\", "/_1/"), parsedArgs.PathMap[2]); } [Theory] [InlineData("", new string[0])] [InlineData(",", new[] { "", "" })] [InlineData(",,", new[] { "," })] [InlineData(",,,", new[] { ",", "" })] [InlineData(",,,,", new[] { ",," })] [InlineData("a,", new[] { "a", "" })] [InlineData("a,b", new[] { "a", "b" })] [InlineData(",,a,,,,,b,,", new[] { ",a,,", "b," })] public void SplitWithDoubledSeparatorEscaping(string str, string[] expected) { AssertEx.Equal(expected, CommandLineParser.SplitWithDoubledSeparatorEscaping(str, ',')); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbParser() { var dir = Path.Combine(WorkingDirectory, "a"); var parsedArgs = DefaultParse(new[] { $@"/pathmap:{dir}=b:\", "a.cs", @"/pdb:a\data.pdb", "/debug:full" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(dir, @"data.pdb"), parsedArgs.PdbPath); // This value is calculate during Emit phases and should be null even in the face of a pathmap targeting it. Assert.Null(parsedArgs.EmitOptions.PdbFilePath); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbEmit() { void AssertPdbEmit(TempDirectory dir, string pdbPath, string pePdbPath, params string[] extraArgs) { var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var defaultArgs = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug:full", $"/pdb:{pdbPath}" }; var isDeterministic = extraArgs.Contains("/deterministic"); var args = defaultArgs.Concat(extraArgs).ToArray(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); Assert.True(File.Exists(pdbPath)); using (var peStream = File.OpenRead(exePath)) { PdbValidation.ValidateDebugDirectory(peStream, null, pePdbPath, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic); } } // Case with no mappings using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, pdbPath); } // Simple mapping using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Simple mapping deterministic using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\", "/deterministic"); } // Partial mapping using (var dir = new DisposableDirectory(Temp)) { dir.CreateDirectory("pdb"); var pdbPath = Path.Combine(dir.Path, @"pdb\a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\pdb\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Legacy feature flag using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"a.pdb", $@"/features:pdb-path-determinism"); } // Unix path map using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"/a.pdb", $@"/pathmap:{dir.Path}=/"); } // Multi-specified path map with mixed slashes using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, "/goo/a.pdb", $"/pathmap:{dir.Path}=/goo,{dir.Path}{PathUtilities.DirectorySeparatorChar}=/bar"); } } [CompilerTrait(CompilerFeature.Determinism)] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void DeterministicPdbsRegardlessOfBitness() { var dir = Temp.CreateDirectory(); var dir32 = dir.CreateDirectory("32"); var dir64 = dir.CreateDirectory("64"); var programExe32 = dir32.CreateFile("Program.exe"); var programPdb32 = dir32.CreateFile("Program.pdb"); var programExe64 = dir64.CreateFile("Program.exe"); var programPdb64 = dir64.CreateFile("Program.pdb"); var sourceFile = dir.CreateFile("Source.cs").WriteAllText(@" using System; using System.Linq; using System.Collections.Generic; namespace N { using I4 = System.Int32; class Program { public static IEnumerable<int> F() { I4 x = 1; yield return 1; yield return x; } public static void Main(string[] args) { dynamic x = 1; const int a = 1; F().ToArray(); Console.WriteLine(x + a); } } }"); var csc32src = $@" using System; using System.Reflection; class Runner {{ static int Main(string[] args) {{ var assembly = Assembly.LoadFrom(@""{s_CSharpCompilerExecutable}""); var program = assembly.GetType(""Microsoft.CodeAnalysis.CSharp.CommandLine.Program""); var main = program.GetMethod(""Main""); return (int)main.Invoke(null, new object[] {{ args }}); }} }} "; var csc32 = CreateCompilationWithMscorlib46(csc32src, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86), assemblyName: "csc32"); var csc32exe = dir.CreateFile("csc32.exe").WriteAllBytes(csc32.EmitToArray()); dir.CopyFile(Path.ChangeExtension(s_CSharpCompilerExecutable, ".exe.config"), "csc32.exe.config"); dir.CopyFile(Path.Combine(Path.GetDirectoryName(s_CSharpCompilerExecutable), "csc.rsp")); var output = ProcessUtilities.RunAndGetOutput(csc32exe.Path, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir32.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir32.Path); Assert.Equal("", output); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir64.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir64.Path); Assert.Equal("", output); AssertEx.Equal(programExe32.ReadAllBytes(), programExe64.ReadAllBytes()); AssertEx.Equal(programPdb32.ReadAllBytes(), programPdb64.ReadAllBytes()); } [WorkItem(7588, "https://github.com/dotnet/roslyn/issues/7588")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Version() { var folderName = Temp.CreateDirectory().ToString(); var argss = new[] { "/version", "a.cs /version /preferreduilang:en", "/version /nologo", "/version /help", }; foreach (var args in argss) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, args, startFolder: folderName); Assert.Equal(s_compilerVersion, output.Trim()); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RefOut() { var dir = Temp.CreateDirectory(); var refDir = dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" public class C { /// <summary>Main method</summary> public static void Main() { System.Console.Write(""Hello""); } /// <summary>Private method</summary> private static void PrivateMethod() { System.Console.Write(""Private""); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.exe", "/refout:ref/a.dll", "/doc:doc.xml", "/deterministic", "/langversion:7", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exe = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exe)); MetadataReaderUtils.VerifyPEMetadata(exe, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C.PrivateMethod()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute" } ); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""M:C.PrivateMethod""> <summary>Private method</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); var output = ProcessUtilities.RunAndGetOutput(exe, startFolder: dir.Path); Assert.Equal("Hello", output.Trim()); var refDll = Path.Combine(refDir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); CleanupAllGeneratedFiles(refDir.Path); } [Fact] public void RefOutWithError() { var dir = Temp.CreateDirectory(); dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() { error(); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refout:ref/a.dll", "/deterministic", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var dll = Path.Combine(dir.Path, "a.dll"); Assert.False(File.Exists(dll)); var refDll = Path.Combine(dir.Path, Path.Combine("ref", "a.dll")); Assert.False(File.Exists(refDll)); Assert.Equal("a.cs(1,39): error CS0103: The name 'error' does not exist in the current context", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void RefOnly() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" using System; class C { /// <summary>Main method</summary> public static void Main() { error(); // semantic error in method body } private event Action E1 { add { } remove { } } private event Action E2; /// <summary>Private Class Field</summary> private int field; /// <summary>Private Struct</summary> private struct S { /// <summary>Private Struct Field</summary> private int field; } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refonly", "/debug", "/deterministic", "/langversion:7", "/doc:doc.xml", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var refDll = Path.Combine(dir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C", "TypeDefinition:S" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); var pdb = Path.Combine(dir.Path, "a.pdb"); Assert.False(File.Exists(pdb)); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""F:C.field""> <summary>Private Class Field</summary> </member> <member name=""T:C.S""> <summary>Private Struct</summary> </member> <member name=""F:C.S.field""> <summary>Private Struct Field</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/define:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '1' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("1").WithLocation(1, 1)); } [Fact] public void CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/langversion:1000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '1000' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("1000").WithLocation(1, 1)); } [Fact, WorkItem(16913, "https://github.com/dotnet/roslyn/issues/16913")] public void CompilingCodeWithMultipleInvalidPreProcessorSymbolsShouldErrorOut() { var parsedArgs = DefaultParse(new[] { "/define:valid1,2invalid,valid3", "/define:4,5,valid6", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid value for '/define'; '2invalid' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("2invalid"), // warning CS2029: Invalid value for '/define'; '4' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("4"), // warning CS2029: Invalid value for '/define'; '5' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("5")); } [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MissingCompilerAssembly() { var dir = Temp.CreateDirectory(); var cscPath = dir.CopyFile(s_CSharpCompilerExecutable).Path; dir.CopyFile(typeof(Compilation).Assembly.Location); // Missing Microsoft.CodeAnalysis.CSharp.dll. var result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(CSharpCompilation).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); // Missing System.Collections.Immutable.dll. dir.CopyFile(typeof(CSharpCompilation).Assembly.Location); result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); } #if NET472 [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void LoadinganalyzerNetStandard13() { var analyzerFileName = "AnalyzerNS13.dll"; var srcFileName = "src.cs"; var analyzerDir = Temp.CreateDirectory(); var analyzerFile = analyzerDir.CreateFile(analyzerFileName).WriteAllBytes(DesktopTestHelpers.CreateCSharpAnalyzerNetStandard13(Path.GetFileNameWithoutExtension(analyzerFileName))); var srcFile = analyzerDir.CreateFile(srcFileName).WriteAllText("public class C { }"); var result = ProcessUtilities.Run(s_CSharpCompilerExecutable, arguments: $"/nologo /t:library /analyzer:{analyzerFileName} {srcFileName}", workingDirectory: analyzerDir.Path); var outputWithoutPaths = Regex.Replace(result.Output, " in .*", ""); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"warning AD0001: Analyzer 'TestAnalyzer' threw an exception of type 'System.NotImplementedException' with message '28'. System.NotImplementedException: 28 at TestAnalyzer.get_SupportedDiagnostics() at Microsoft.CodeAnalysis.Diagnostics.AnalyzerManager.AnalyzerExecutionContext.<>c__DisplayClass20_0.<ComputeDiagnosticDescriptors>b__0(Object _) at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info) -----", outputWithoutPaths); Assert.Equal(0, result.ExitCode); } #endif [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=484417")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MicrosoftDiaSymReaderNativeAltLoadPath() { var dir = Temp.CreateDirectory(); var cscDir = Path.GetDirectoryName(s_CSharpCompilerExecutable); // copy csc and dependencies except for DSRN: foreach (var filePath in Directory.EnumerateFiles(cscDir)) { var fileName = Path.GetFileName(filePath); if (fileName.StartsWith("csc") || fileName.StartsWith("System.") || fileName.StartsWith("Microsoft.") && !fileName.StartsWith("Microsoft.DiaSymReader.Native")) { dir.CopyFile(filePath); } } dir.CreateFile("Source.cs").WriteAllText("class C { void F() { } }"); var cscCopy = Path.Combine(dir.Path, "csc.exe"); var arguments = "/nologo /t:library /debug:full Source.cs"; // env variable not set (deterministic) -- DSRN is required: var result = ProcessUtilities.Run(cscCopy, arguments + " /deterministic", workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences( "error CS0041: Unexpected error writing debug information -- 'Unable to load DLL 'Microsoft.DiaSymReader.Native.amd64.dll': " + "The specified module could not be found. (Exception from HRESULT: 0x8007007E)'", result.Output.Trim()); // env variable not set (non-deterministic) -- globally registered SymReader is picked up: result = ProcessUtilities.Run(cscCopy, arguments, workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences("", result.Output.Trim()); // env variable set: result = ProcessUtilities.Run( cscCopy, arguments + " /deterministic", workingDirectory: dir.Path, additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", cscDir) }); Assert.Equal("", result.Output.Trim()); } [ConditionalFact(typeof(WindowsOnly))] [WorkItem(21935, "https://github.com/dotnet/roslyn/issues/21935")] public void PdbPathNotEmittedWithoutPdb() { var dir = Temp.CreateDirectory(); var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var args = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug-" }; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); using (var peStream = File.OpenRead(exePath)) using (var peReader = new PEReader(peStream)) { var debugDirectory = peReader.PEHeaders.PEHeader.DebugTableDirectory; Assert.Equal(0, debugDirectory.Size); Assert.Equal(0, debugDirectory.RelativeVirtualAddress); } } [Fact] public void StrongNameProviderWithCustomTempPath() { var tempDir = Temp.CreateDirectory(); var workingDir = Temp.CreateDirectory(); workingDir.CreateFile("a.cs"); var buildPaths = new BuildPaths(clientDir: "", workingDir: workingDir.Path, sdkDir: null, tempDir: tempDir.Path); var csc = new MockCSharpCompiler(null, buildPaths, args: new[] { "/features:UseLegacyStrongNameProvider", "/nostdlib", "a.cs" }); var comp = csc.CreateCompilation(new StringWriter(), new TouchedFileLogger(), errorLogger: null); Assert.True(!comp.SignUsingBuilder); } public class QuotedArgumentTests : CommandLineTestBase { private static readonly string s_rootPath = ExecutionConditionUtil.IsWindows ? @"c:\" : "/"; private void VerifyQuotedValid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); } private void VerifyQuotedInvalid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.True(args.Errors.Length > 0); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void DebugFlag() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var list = new List<Tuple<string, DebugInformationFormat>>() { Tuple.Create("portable", DebugInformationFormat.PortablePdb), Tuple.Create("full", platformPdbKind), Tuple.Create("pdbonly", platformPdbKind), Tuple.Create("embedded", DebugInformationFormat.Embedded) }; foreach (var tuple in list) { VerifyQuotedValid("debug", tuple.Item1, tuple.Item2, x => x.EmitOptions.DebugInformationFormat); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void CodePage() { VerifyQuotedValid("codepage", "1252", 1252, x => x.Encoding.CodePage); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void Target() { var list = new List<Tuple<string, OutputKind>>() { Tuple.Create("exe", OutputKind.ConsoleApplication), Tuple.Create("winexe", OutputKind.WindowsApplication), Tuple.Create("library", OutputKind.DynamicallyLinkedLibrary), Tuple.Create("module", OutputKind.NetModule), Tuple.Create("appcontainerexe", OutputKind.WindowsRuntimeApplication), Tuple.Create("winmdobj", OutputKind.WindowsRuntimeMetadata) }; foreach (var tuple in list) { VerifyQuotedInvalid("target", tuple.Item1, tuple.Item2, x => x.CompilationOptions.OutputKind); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void PlatformFlag() { var list = new List<Tuple<string, Platform>>() { Tuple.Create("x86", Platform.X86), Tuple.Create("x64", Platform.X64), Tuple.Create("itanium", Platform.Itanium), Tuple.Create("anycpu", Platform.AnyCpu), Tuple.Create("anycpu32bitpreferred",Platform.AnyCpu32BitPreferred), Tuple.Create("arm", Platform.Arm) }; foreach (var tuple in list) { VerifyQuotedValid("platform", tuple.Item1, tuple.Item2, x => x.CompilationOptions.Platform); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void WarnFlag() { VerifyQuotedValid("warn", "1", 1, x => x.CompilationOptions.WarningLevel); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void LangVersionFlag() { VerifyQuotedValid("langversion", "2", LanguageVersion.CSharp2, x => x.ParseOptions.LanguageVersion); } } [Fact] [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] public void InvalidPathCharacterInPathMap() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pathmap:test\\=\"", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS8101: The pathmap option was incorrectly formatted.", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void InvalidPathCharacterInPdbPath() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pdb:test\\?.pdb", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2021: File name 'test\\?.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerParserWarningAsError() { string source = @" class C { long M(int i) { // warning CS0078 : The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity return 0l; } } "; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that parser warning CS0078 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0078"); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS0078", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0078", output, StringComparison.Ordinal); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_LowercaseEllSuffix, "l"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerSyntaxWarning() { // warning CS1522: Empty switch block // NOTE: Empty switch block warning is reported by the C# language parser string source = @" class C { void M(int i) { switch (i) { } } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS1522 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS1522"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_EmptySwitch), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains($"info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS1522", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerSemanticWarning() { string source = @" class C { // warning CS0169: The field 'C.f' is never used private readonly int f; }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS0169 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0169"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_UnreferencedField, "C.f"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS0169", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSyntaxError() { // error CS1001: Identifier expected string source = @" class { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler syntax error CS1001 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS1001", output, StringComparison.Ordinal); // Verify that compiler syntax error CS1001 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS1001")); Assert.Contains("error CS1001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSemanticError() { // error CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) string source = @" class C { void M(UndefinedType x) { } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler error CS0246 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0246", output, StringComparison.Ordinal); // Verify that compiler error CS0246 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS0246")); Assert.Contains("error CS0246", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_AnalyzerWarning() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer warning is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, analyzer.Descriptor.MessageFormat, suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that analyzer warning is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that "NotConfigurable" analyzer warning cannot be suppressed with diagnostic suppressor. analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: false); suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_AnalyzerError() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer error is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Error, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer error cannot be suppressed with diagnostic suppressor. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestCategoryBasedBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify category based configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify category based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify category based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify disabled by default analyzer is not enabled by category based configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify disabled by default analyzer is not enabled by category based configuration in global config analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" is_global=true dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer via global config analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; // Verify bulk configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify bulk configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify bulk configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify bulk configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify bulk configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify disabled by default analyzer is not enabled by bulk configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestMixedCategoryBasedAndBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration before bulk analyzer diagnostic configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_analyzer_diagnostic.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration after bulk analyzer diagnostic configuration is respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in analyzer config. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in ruleset. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText); } private void TestBulkAnalyzerConfigurationCore( NamedTypeAnalyzerWithConfigurableEnabledByDefault analyzer, string analyzerConfigText, bool errorlog, ReportDiagnostic expectedDiagnosticSeverity, string rulesetText = null, bool noWarn = false) { var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(analyzerConfigText); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{diagnosticId}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } if (rulesetText != null) { var rulesetFile = CreateRuleSetFile(rulesetText); arguments = arguments.Append($"/ruleset:{rulesetFile.Path}"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = expectedDiagnosticSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); var prefix = expectedDiagnosticSeverity switch { ReportDiagnostic.Error => "error", ReportDiagnostic.Warn => "warning", ReportDiagnostic.Info => errorlog ? "info" : null, ReportDiagnostic.Hidden => null, ReportDiagnostic.Suppress => null, _ => throw ExceptionUtilities.UnexpectedValue(expectedDiagnosticSeverity) }; if (prefix == null) { Assert.DoesNotContain(diagnosticId, outWriter.ToString()); } else { Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", outWriter.ToString()); } } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void CompilerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (warnAsError) { additionalArgs = additionalArgs.Append("/warnaserror").AsArray(); } var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = warnAsError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !warnAsError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !warnAsError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerConfigSeverityEscalationToErrorDoesNotEmit(bool analyzerConfigSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (analyzerConfigSetToError) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = error"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } var expectedErrorCount = analyzerConfigSetToError ? 1 : 0; var expectedWarningCount = !analyzerConfigSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = analyzerConfigSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !analyzerConfigSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !analyzerConfigSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !analyzerConfigSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void RulesetSeverityEscalationToErrorDoesNotEmit(bool rulesetSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (rulesetSetToError) { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""CS0169"" Action=""Error"" /> </Rules> </RuleSet> "; var rulesetFile = CreateRuleSetFile(source); additionalArgs = additionalArgs.Append("/ruleset:" + rulesetFile.Path).ToArray(); } var expectedErrorCount = rulesetSetToError ? 1 : 0; var expectedWarningCount = !rulesetSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = rulesetSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !rulesetSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !rulesetSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !rulesetSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C { }"); var additionalArgs = warnAsError ? new[] { "/warnaserror" } : null; var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount, analyzers: new[] { new WarningDiagnosticAnalyzer() }); var expectedDiagnosticSeverity = warnAsError ? "error" : "warning"; Assert.Contains($"{expectedDiagnosticSeverity} {WarningDiagnosticAnalyzer.Warning01.Id}", output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); } // Currently, configuring no location diagnostics through editorconfig is not supported. [Theory(Skip = "https://github.com/dotnet/roslyn/issues/38042")] [CombinatorialData] public void AnalyzerConfigRespectedForNoLocationDiagnostic(ReportDiagnostic reportDiagnostic, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new AnalyzerWithNoLocationDiagnostics(isEnabledByDefault); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, reportDiagnostic, noWarn, errorlog); } [WorkItem(37876, "https://github.com/dotnet/roslyn/issues/37876")] [Theory] [CombinatorialData] public void AnalyzerConfigRespectedForDisabledByDefaultDiagnostic(ReportDiagnostic analyzerConfigSeverity, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity: DiagnosticSeverity.Warning); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, analyzerConfigSeverity, noWarn, errorlog); } private void TestAnalyzerConfigRespectedCore(DiagnosticAnalyzer analyzer, DiagnosticDescriptor descriptor, ReportDiagnostic analyzerConfigSeverity, bool noWarn, bool errorlog) { if (analyzerConfigSeverity == ReportDiagnostic.Default) { // "dotnet_diagnostic.ID.severity = default" is not supported. return; } var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{descriptor.Id}.severity = {analyzerConfigSeverity.ToAnalyzerConfigString()}"); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{descriptor.Id}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = !noWarn && analyzerConfigSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. if (!noWarn && (analyzerConfigSeverity == ReportDiagnostic.Error || analyzerConfigSeverity == ReportDiagnostic.Warn || (analyzerConfigSeverity == ReportDiagnostic.Info && errorlog))) { var prefix = analyzerConfigSeverity == ReportDiagnostic.Error ? "error" : analyzerConfigSeverity == ReportDiagnostic.Warn ? "warning" : "info"; Assert.Contains($"{prefix} {descriptor.Id}: {descriptor.MessageFormat}", outWriter.ToString()); } else { Assert.DoesNotContain(descriptor.Id.ToString(), outWriter.ToString()); } } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public void IsUserConfiguredGeneratedCodeInAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M(C? c) { _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. } }"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable" }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = true var analyzerConfigFile = dir.CreateFile(".editorconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = true"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.DoesNotContain("warning CS8602", output, StringComparison.Ordinal); // warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source. Assert.Contains("warning CS8669", output, StringComparison.Ordinal); // generated_code = false analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = false"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = auto analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = auto"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); } [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void TestAnalyzerFilteringBasedOnSeverity(DiagnosticSeverity defaultSeverity, bool errorlog) { // This test verifies that analyzer execution is skipped at build time for the following: // 1. Analyzer reporting Hidden diagnostics // 2. Analyzer reporting Info diagnostics, when /errorlog is not specified var analyzerShouldBeSkipped = defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog; // We use an analyzer that throws an exception on every analyzer callback. // So an AD0001 analyzer exception diagnostic is reported if analyzer executed, otherwise not. var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var args = new[] { "/nologo", "/t:library", "/preferreduilang:en", src.Path }; if (errorlog) args = args.Append("/errorlog:errorlog"); var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { Assert.Contains("warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+NamedTypeAnalyzerWithConfigurableEnabledByDefault' threw an exception of type 'System.NotImplementedException'", output, StringComparison.Ordinal); } } [WorkItem(47017, "https://github.com/dotnet/roslyn/issues/47017")] [CombinatorialData, Theory] public void TestWarnAsErrorMinusDoesNotEnableDisabledByDefaultAnalyzers(DiagnosticSeverity defaultSeverity, bool isEnabledByDefault) { // This test verifies that '/warnaserror-:DiagnosticId' does not affect if analyzers are executed or skipped.. // Setup the analyzer to always throw an exception on analyzer callbacks for cases where we expect analyzer execution to be skipped: // 1. Disabled by default analyzer, i.e. 'isEnabledByDefault == false'. // 2. Default severity Hidden/Info: We only execute analyzers reporting Warning/Error severity diagnostics on command line builds. var analyzerShouldBeSkipped = !isEnabledByDefault || defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info; var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity, throwOnAllNamedTypes: analyzerShouldBeSkipped); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); // Verify '/warnaserror-:DiagnosticId' behavior. var args = new[] { "/warnaserror+", $"/warnaserror-:{diagnosticId}", "/nologo", "/t:library", "/preferreduilang:en", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedExitCode = !analyzerShouldBeSkipped && defaultSeverity == DiagnosticSeverity.Error ? 1 : 0; Assert.Equal(expectedExitCode, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { var prefix = defaultSeverity == DiagnosticSeverity.Warning ? "warning" : "error"; Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", output); } } [WorkItem(49446, "https://github.com/dotnet/roslyn/issues/49446")] [Theory] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when config file bumps severity to 'Warning' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and no config file setting is specified. [InlineData(false, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' has no effect when default severity is 'Info' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] public void TestWarnAsErrorMinusDoesNotNullifyEditorConfig( bool warnAsErrorMinus, DiagnosticSeverity defaultSeverity, DiagnosticSeverity? severityInConfigFile, DiagnosticSeverity expectedEffectiveSeverity) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: false); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var additionalFlags = new[] { "/warnaserror+" }; if (severityInConfigFile.HasValue) { var severityString = DiagnosticDescriptor.MapSeverityToReport(severityInConfigFile.Value).ToAnalyzerConfigString(); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {severityString}"); additionalFlags = additionalFlags.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray(); } if (warnAsErrorMinus) { additionalFlags = additionalFlags.Append($"/warnaserror-:{diagnosticId}").ToArray(); } int expectedWarningCount = 0, expectedErrorCount = 0; switch (expectedEffectiveSeverity) { case DiagnosticSeverity.Warning: expectedWarningCount = 1; break; case DiagnosticSeverity.Error: expectedErrorCount = 1; break; default: throw ExceptionUtilities.UnexpectedValue(expectedEffectiveSeverity); } VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, expectedWarningCount: expectedWarningCount, expectedErrorCount: expectedErrorCount, additionalFlags: additionalFlags, analyzers: new[] { analyzer }); } [Fact] public void SourceGenerators_EmbeddedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, $"generatedSource.cs"), generatedSource } }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void TestSourceGeneratorsWithAnalyzers(bool includeCurrentAssemblyAsAnalyzerReference, bool skipAnalyzers) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); // 'skipAnalyzers' should have no impact on source generator execution, but should prevent analyzer execution. var skipAnalyzersFlag = "/skipAnalyzers" + (skipAnalyzers ? "+" : "-"); // Verify analyzers were executed only if both the following conditions were satisfied: // 1. Current assembly was added as an analyzer reference, i.e. "includeCurrentAssemblyAsAnalyzerReference = true" and // 2. We did not explicitly request skipping analyzers, i.e. "skipAnalyzers = false". var expectedAnalyzerExecution = includeCurrentAssemblyAsAnalyzerReference && !skipAnalyzers; // 'WarningDiagnosticAnalyzer' generates a warning for each named type. // We expect two warnings for this test: type "C" defined in source and the source generator defined type. // Additionally, we also have an analyzer that generates "warning CS8032: An instance of analyzer cannot be created" var expectedWarningCount = expectedAnalyzerExecution ? 3 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference, expectedWarningCount: expectedWarningCount, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe", skipAnalyzersFlag }, generators: new[] { generator }); // Verify source generator was executed, regardless of the value of 'skipAnalyzers'. var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, "generatedSource.cs"), generatedSource } }, dir, true); if (expectedAnalyzerExecution) { Assert.Contains("warning Warning01", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); } else { Assert.Empty(output); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_EmbeddedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generator1Prefix, source1Name), source1}, { Path.Combine(dir.Path, generator2Prefix, source2Name), source2}, }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_WriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_OverwriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource1 = "class D { } class E { }"; var generator1 = new SingleFileTestGenerator(generatedSource1, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator1 }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator1); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource1 } } } }); var generatedSource2 = "public class D { }"; var generator2 = new SingleFileTestGenerator(generatedSource2, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator2 }, analyzers: null); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_WriteGeneratedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generator1Prefix), new() { { source1Name, source1 } } }, { Path.Combine(generatedDir.Path, generator2Prefix), new() { { source2Name, source2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [ConditionalFact(typeof(DesktopClrOnly))] //CoreCLR doesn't support SxS loading [WorkItem(47990, "https://github.com/dotnet/roslyn/issues/47990")] public void SourceGenerators_SxS_AssemblyLoading() { // compile the generators var dir = Temp.CreateDirectory(); var snk = Temp.CreateFile("TestKeyPair_", ".snk", dir.Path).WriteAllBytes(TestResources.General.snKey); var src = dir.CreateFile("generator.cs"); var virtualSnProvider = new DesktopStrongNameProvider(ImmutableArray.Create(dir.Path)); string createGenerator(string version) { var generatorSource = $@" using Microsoft.CodeAnalysis; [assembly:System.Reflection.AssemblyVersion(""{version}"")] [Generator] public class TestGenerator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ context.AddSource(""generatedSource.cs"", ""//from version {version}""); }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var path = Path.Combine(dir.Path, Guid.NewGuid().ToString() + ".dll"); var comp = CreateEmptyCompilation(source: generatorSource, references: TargetFrameworkUtil.NetStandard20References.Add(MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly)), options: TestOptions.DebugDll.WithCryptoKeyFile(Path.GetFileName(snk.Path)).WithStrongNameProvider(virtualSnProvider), assemblyName: "generator"); comp.VerifyDiagnostics(); comp.Emit(path); return path; } var gen1 = createGenerator("1.0.0.0"); var gen2 = createGenerator("2.0.0.0"); var generatedDir = dir.CreateDirectory("generated"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/analyzer:" + gen1, "/analyzer:" + gen2 }.ToArray()); // This is wrong! Both generators are writing the same file out, over the top of each other // See https://github.com/dotnet/roslyn/issues/47990 ValidateWrittenSources(new() { // { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 1.0.0.0" } } }, { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 2.0.0.0" } } } }); } [Fact] public void SourceGenerators_DoNotWriteGeneratedSources_When_No_Directory_Supplied() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); ValidateWrittenSources(new() { { generatedDir.Path, new() } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_Error_When_GeneratedDir_NotExist() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDirPath = Path.Combine(dir.Path, "noexist"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); var output = VerifyOutput(dir, src, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDirPath, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); Assert.Contains("CS0016:", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_GeneratedDir_Has_Spaces() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated files"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void ParseGeneratedFilesOut() { string root = PathUtilities.IsUnixLikePlatform ? "/" : "c:\\"; string baseDirectory = Path.Combine(root, "abc", "def"); var parsedArgs = DefaultParse(new[] { @"/generatedfilesout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:\"\"")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:outdir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""outdir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:out dir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""out dir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); var absPath = Path.Combine(root, "outdir"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); absPath = Path.Combine(root, "generated files"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); } [Fact] public void SourceGenerators_Error_When_NoDirectoryArgumentGiven() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var output = VerifyOutput(dir, src, expectedErrorCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:", "/langversion:preview", "/out:embed.exe" }); Assert.Contains("error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_ReportedWrittenFiles_To_TouchedFilesLogger() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, $"/touchedfiles:{dir.Path}/touched", "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var touchedFiles = Directory.GetFiles(dir.Path, "touched*"); Assert.Equal(2, touchedFiles.Length); string[] writtenText = File.ReadAllLines(Path.Combine(dir.Path, "touched.write")); Assert.Equal(2, writtenText.Length); Assert.EndsWith("EMBED.EXE", writtenText[0], StringComparison.OrdinalIgnoreCase); Assert.EndsWith("GENERATEDSOURCE.CS", writtenText[1], StringComparison.OrdinalIgnoreCase); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44087")] public void SourceGeneratorsAndAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key = value"); var generator = new SingleFileTestGenerator("public class D {}", "generated.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path }, generators: new[] { generator }, analyzers: null); } [Fact] public void SourceGeneratorsCanReadAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig1 = dir.CreateFile(".globaleditorconfig").WriteAllText(@" is_global = true key1 = value1 [*.cs] key2 = value2 [*.vb] key3 = value3"); var analyzerConfig2 = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key4 = value4 [*.vb] key5 = value5"); var subDir = dir.CreateDirectory("subDir"); var analyzerConfig3 = subDir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key6 = value6 [*.vb] key7 = value7"); var generator = new CallbackGenerator((ic) => { }, (gc) => { // can get the global options var globalOptions = gc.AnalyzerConfigOptions.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // can get the options for class C var classOptions = gc.AnalyzerConfigOptions.GetOptions(gc.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); }); var args = new[] { "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, "/analyzerconfig:" + analyzerConfig3.Path, "/t:library", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, generators: ImmutableArray.Create<ISourceGenerator>(generator)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); // test for both the original tree and the generated one var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; // get the global options var globalOptions = provider.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // get the options for class C var classOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); // get the options for generated class D var generatedOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.Last()); Assert.True(generatedOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(generatedOptions.TryGetValue("key2", out _)); Assert.False(generatedOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(generatedOptions.TryGetValue("key5", out _)); Assert.False(generatedOptions.TryGetValue("key6", out _)); Assert.False(generatedOptions.TryGetValue("key7", out _)); } [Theory] [CombinatorialData] public void SourceGeneratorsRunRegardlessOfLanguageVersion(LanguageVersion version) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@"class C {}"); var generator = new CallbackGenerator(i => { }, e => throw null); var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:" + version.ToDisplayString() }, generators: new[] { generator }, expectedWarningCount: 1, expectedErrorCount: 1, expectedExitCode: 0); Assert.Contains("CS8785: Generator 'CallbackGenerator' failed to generate source.", output); } [DiagnosticAnalyzer(LanguageNames.CSharp)] private sealed class FieldAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor _rule = new DiagnosticDescriptor("Id", "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration); } private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) { } } [Fact] [WorkItem(44000, "https://github.com/dotnet/roslyn/issues/44000")] public void TupleField_ForceComplete() { var source = @"namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { Item1 = item1; } } }"; var srcFile = Temp.CreateFile().WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler( null, WorkingDirectory, new[] { "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new FieldAnalyzer())); // at least one analyzer required var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Empty(output); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void GlobalAnalyzerConfigsAllowedInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" is_global = true "; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); } [Fact] public void GlobalAnalyzerConfigMultipleSetKeys() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfigFile = dir.CreateFile(".globalconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 option1 = abc"); var analyzerConfigFile2 = dir.CreateFile(".globalconfig2"); var analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 option1 = def"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'Global Section'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'Global Section'", output, StringComparison.Ordinal); analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = abc"); analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = def"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'file.cs'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'/file.cs'", output, StringComparison.Ordinal); } [Fact] public void GlobalAnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key1 = value1 [*.txt] key2 = value2"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true key3 = value3"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzerconfig:" + globalConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032,Warning01", "/additionalfile:" + additionalFile.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = provider.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("key1", out string val)); Assert.Equal("value1", val); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.True(options.TryGetValue("key2", out val)); Assert.Equal("value2", val); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GlobalOptions; Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigDiagnosticOptionsCanBeOverridenByCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.CS0164.severity = error; "); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.CS0164.severity = warning; "); var none = Array.Empty<TempFile>(); var globalOnly = new[] { globalConfig }; var globalAndSpecific = new[] { globalConfig, analyzerConfig }; // by default a warning, which can be suppressed via cmdline verify(configs: none, expectedWarnings: 1); verify(configs: none, noWarn: "CS0164", expectedWarnings: 0); // the global analyzer config ups the warning to an error, but the cmdline setting overrides it verify(configs: globalOnly, expectedErrors: 1); verify(configs: globalOnly, noWarn: "CS0164", expectedWarnings: 0); verify(configs: globalOnly, noWarn: "164", expectedWarnings: 0); // cmdline can be shortened, but still works // the editor config downgrades the error back to warning, but the cmdline setting overrides it verify(configs: globalAndSpecific, expectedWarnings: 1); verify(configs: globalAndSpecific, noWarn: "CS0164", expectedWarnings: 0); void verify(TempFile[] configs, int expectedWarnings = 0, int expectedErrors = 0, string noWarn = "0") => VerifyOutput(dir, src, expectedErrorCount: expectedErrors, expectedWarningCount: expectedWarnings, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: null, additionalFlags: configs.SelectAsArray(c => "/analyzerconfig:" + c.Path) .Add("/noWarn:" + noWarn).ToArray()); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSpecificDiagnosticOptionsOverrideGeneralCommandLineOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = none; "); VerifyOutput(dir, src, additionalFlags: new[] { "/warnaserror+", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false); } [Theory, CombinatorialData] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void WarnAsErrorIsRespectedForForWarningsConfiguredInRulesetOrGlobalConfig(bool useGlobalConfig) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var additionalFlags = new[] { "/warnaserror+" }; if (useGlobalConfig) { var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = warning; "); additionalFlags = additionalFlags.Append("/analyzerconfig:" + globalConfig.Path).ToArray(); } else { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""15.0""> <Rules AnalyzerId=""Compiler"" RuleNamespace=""Compiler""> <Rule Id=""CS0164"" Action=""Warning"" /> </Rules> </RuleSet> "; _ = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); additionalFlags = additionalFlags.Append("/ruleset:Rules.ruleset").ToArray(); } VerifyOutput(dir, src, additionalFlags: additionalFlags, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSectionsDoNotOverrideCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true [{PathUtilities.NormalizeWithForwardSlash(src.Path)}] dotnet_diagnostic.CS0164.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:0164", "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 0, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigCanSetDiagnosticWithNoLocation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.Warning01.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:Warning01", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); } [Theory, CombinatorialData] public void TestAdditionalFileAnalyzer(bool registerFromInitialize) { var srcDirectory = Temp.CreateDirectory(); var source = "class C { }"; var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); var additionalText = "Additional Text"; var additionalFile = srcDirectory.CreateFile("b.txt"); additionalFile.WriteAllText(additionalText); var diagnosticSpan = new TextSpan(2, 2); var analyzer = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/additionalfile:" + additionalFile.Path }, analyzers: analyzer); Assert.Contains("b.txt(1,3): warning ID0001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcDirectory.Path); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:CS0169" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_CompilerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var src = @" class C { int _f; // CS0169: unused field }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, diagnosticId: "CS0169", analyzerConfigSeverity, additionalArg, expectError, expectWarning); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:DiagnosticId" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_AnalyzerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var src = @"class C { }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, CompilationAnalyzerWithSeverity.DiagnosticId, analyzerConfigSeverity, additionalArg, expectError, expectWarning, analyzer); } private void TestCompilationOptionsOverrideAnalyzerConfigCore( string source, string diagnosticId, string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning, params DiagnosticAnalyzer[] analyzers) { Assert.True(!expectError || !expectWarning); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(source); var additionalArgs = Array.Empty<string>(); if (analyzerConfigSeverity != null) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {analyzerConfigSeverity}"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } if (!string.IsNullOrEmpty(additionalArg)) { additionalArgs = additionalArgs.Append(additionalArg); } var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectError ? 1 : 0, expectedWarningCount: expectWarning ? 1 : 0, analyzers: analyzers); if (expectError) { Assert.Contains($"error {diagnosticId}", output); } else if (expectWarning) { Assert.Contains($"warning {diagnosticId}", output); } else { Assert.DoesNotContain(diagnosticId, output); } } [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a coreclr targeting generator on net framework / mono")] public void TestGeneratorsCantTargetNetFramework() { var directory = Temp.CreateDirectory(); var src = directory.CreateFile("test.cs").WriteAllText(@" class C { }"); // core var coreGenerator = emitGenerator(".NETCoreApp,Version=v5.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + coreGenerator }); // netstandard var nsGenerator = emitGenerator(".NETStandard,Version=v2.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + nsGenerator }); // no target var ntGenerator = emitGenerator(targetFramework: null); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + ntGenerator }); // framework var frameworkGenerator = emitGenerator(".NETFramework,Version=v4.7.2"); var output = VerifyOutput(directory, src, expectedWarningCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8850", output); // ref's net fx Assert.Contains("CS8033", output); // no analyzers in assembly // framework, suppressed output = VerifyOutput(directory, src, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850", "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8033", output); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850,CS8033", "/analyzer:" + frameworkGenerator }); string emitGenerator(string targetFramework) { string targetFrameworkAttributeText = targetFramework is object ? $"[assembly: System.Runtime.Versioning.TargetFramework(\"{targetFramework}\")]" : string.Empty; string generatorSource = $@" using Microsoft.CodeAnalysis; {targetFrameworkAttributeText} [Generator] public class Generator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var directory = Temp.CreateDirectory(); var generatorPath = Path.Combine(directory.Path, "generator.dll"); var compilation = CSharpCompilation.Create($"generator_{targetFramework}", new[] { CSharpSyntaxTree.ParseText(generatorSource) }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, new[] { MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly) }), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); compilation.VerifyDiagnostics(); var result = compilation.Emit(generatorPath); Assert.True(result.Success); return generatorPath; } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal abstract class CompilationStartedAnalyzer : DiagnosticAnalyzer { public abstract override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public abstract void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class HiddenDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Hidden01 = new DiagnosticDescriptor("Hidden01", "", "Throwing a diagnostic for #region", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Hidden02 = new DiagnosticDescriptor("Hidden02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Hidden01, Hidden02); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(Hidden01, context.Node.GetLocation())); } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.RegionDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class InfoDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Info01 = new DiagnosticDescriptor("Info01", "", "Throwing a diagnostic for #pragma restore", "", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Info01); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { if ((context.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.RestoreKeyword)) { context.ReportDiagnostic(Diagnostic.Create(Info01, context.Node.GetLocation())); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.PragmaWarningDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class WarningDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Warning01 = new DiagnosticDescriptor("Warning01", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Warning01); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSymbolAction( (symbolContext) => { symbolContext.ReportDiagnostic(Diagnostic.Create(Warning01, symbolContext.Symbol.Locations.First())); }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class ErrorDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Error01 = new DiagnosticDescriptor("Error01", "", "Throwing a diagnostic for #pragma disable", "", DiagnosticSeverity.Error, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Error02 = new DiagnosticDescriptor("Error02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Error01, Error02); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction( (nodeContext) => { if ((nodeContext.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword)) { nodeContext.ReportDiagnostic(Diagnostic.Create(Error01, nodeContext.Node.GetLocation())); } }, SyntaxKind.PragmaWarningDirectiveTrivia ); } } }
// 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.ComponentModel; using System.Globalization; using System.IO; using System.IO.MemoryMappedFiles; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.DiaSymReader; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Roslyn.Test.Utilities.SharedResourceHelpers; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public class CommandLineTests : CommandLineTestBase { #if NETCOREAPP private static readonly string s_CSharpCompilerExecutable; private static readonly string s_DotnetCscRun; #else private static readonly string s_CSharpCompilerExecutable = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.exe")); private static readonly string s_DotnetCscRun = ExecutionConditionUtil.IsMono ? "mono" : string.Empty; #endif private static readonly string s_CSharpScriptExecutable; private static readonly string s_compilerVersion = CommonCompiler.GetProductVersion(typeof(CommandLineTests)); static CommandLineTests() { #if NETCOREAPP var cscDllPath = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.dll")); var dotnetExe = DotNetCoreSdk.ExePath; var netStandardDllPath = AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(assembly => !assembly.IsDynamic && assembly.Location.EndsWith("netstandard.dll")).Location; var netStandardDllDir = Path.GetDirectoryName(netStandardDllPath); // Since we are using references based on the UnitTest's runtime, we need to use // its runtime config when executing out program. var runtimeConfigPath = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "runtimeconfig.json"); s_CSharpCompilerExecutable = $@"""{dotnetExe}"" ""{cscDllPath}"" /r:""{netStandardDllPath}"" /r:""{netStandardDllDir}/System.Private.CoreLib.dll"" /r:""{netStandardDllDir}/System.Console.dll"" /r:""{netStandardDllDir}/System.Runtime.dll"""; s_DotnetCscRun = $@"""{dotnetExe}"" exec --runtimeconfig ""{runtimeConfigPath}"""; s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.dll", Path.Combine("csi", "csi.dll")); #else s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.exe", Path.Combine("csi", "csi.exe")); #endif } private class TestCommandLineParser : CSharpCommandLineParser { private readonly Dictionary<string, string> _responseFiles; private readonly Dictionary<string, string[]> _recursivePatterns; private readonly Dictionary<string, string[]> _patterns; public TestCommandLineParser( Dictionary<string, string> responseFiles = null, Dictionary<string, string[]> patterns = null, Dictionary<string, string[]> recursivePatterns = null, bool isInteractive = false) : base(isInteractive) { _responseFiles = responseFiles; _recursivePatterns = recursivePatterns; _patterns = patterns; } internal override IEnumerable<string> EnumerateFiles(string directory, string fileNamePattern, SearchOption searchOption) { var key = directory + "|" + fileNamePattern; if (searchOption == SearchOption.TopDirectoryOnly) { return _patterns[key]; } else { return _recursivePatterns[key]; } } internal override TextReader CreateTextFileReader(string fullPath) { return new StringReader(_responseFiles[fullPath]); } } private CSharpCommandLineArguments ScriptParse(IEnumerable<string> args, string baseDirectory) { return CSharpCommandLineParser.Script.Parse(args, baseDirectory, SdkDirectory); } private CSharpCommandLineArguments FullParse(string commandLine, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null) { sdkDirectory = sdkDirectory ?? SdkDirectory; var args = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: true); return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } [ConditionalFact(typeof(WindowsDesktopOnly))] [WorkItem(34101, "https://github.com/dotnet/roslyn/issues/34101")] public void SuppressedWarnAsErrorsStillEmit() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" #pragma warning disable 1591 public class P { public static void Main() {} }"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/errorlog:errorlog", $"/doc:{docName}", "/warnaserror", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); string exePath = Path.Combine(dir.Path, "temp.exe"); Assert.True(File.Exists(exePath)); var result = ProcessUtilities.Run(exePath, arguments: ""); Assert.Equal(0, result.ExitCode); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void XmlMemoryMapped() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C {}"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", $"/doc:{docName}", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var xmlPath = Path.Combine(dir.Path, docName); using (var fileStream = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var mmf = MemoryMappedFile.CreateFromFile(fileStream, "xmlMap", 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true)) { exitCode = cmd.Run(outWriter); Assert.StartsWith($"error CS0016: Could not write to output file '{xmlPath}' -- ", outWriter.ToString()); Assert.Equal(1, exitCode); } } [Fact] public void SimpleAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none dotnet_diagnostic.Warning01.severity = none my_option = my_val [*.txt] dotnet_diagnostic.cs0169.severity = none my_option2 = my_val2"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032", "/additionalfile:" + additionalFile.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var compilerTreeOptions = comp.Options.SyntaxTreeOptionsProvider; Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "cs0169", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "warning01", CancellationToken.None, out severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); var analyzerOptions = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = analyzerOptions.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option", out string val)); Assert.Equal("my_val", val); Assert.False(options.TryGetValue("my_option2", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); options = analyzerOptions.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option2", out val)); Assert.Equal("my_val2", val); Assert.False(options.TryGetValue("my_option", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); } [Fact] public void AnalyzerConfigBadSeverity() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = garbage"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal( $@"warning InvalidSeverityInAnalyzerConfig: The diagnostic 'cs0169' was given an invalid severity 'garbage' in the analyzer config file at '{analyzerConfig.Path}'. test.cs(4,9): warning CS0169: The field 'C._f' is never used ", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigsInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" [*.cs] dotnet_diagnostic.cs0169.severity = suppress"; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $"error CS8700: Multiple analyzer config files cannot be in the same directory ('{dir.Path}').", outWriter.ToString().TrimEnd()); } // This test should only run when the machine's default encoding is shift-JIS [ConditionalFact(typeof(WindowsDesktopOnly), typeof(HasShiftJisDefaultEncoding), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompileShiftJisOnShiftJis() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", src.Path }); Assert.Null(cmd.Arguments.Encoding); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RunWithShiftJisFile() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/codepage:932", src.Path }); Assert.Equal(932, cmd.Arguments.Encoding?.WindowsCodePage); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompilerBinariesAreAnyCPU() { Assert.Equal(ProcessorArchitecture.MSIL, AssemblyName.GetAssemblyName(s_CSharpCompilerExecutable).ProcessorArchitecture); } [Fact] public void ResponseFiles1() { string rsp = Temp.CreateFile().WriteAllText(@" /r:System.dll /nostdlib # this is ignored System.Console.WriteLine(""*?""); # this is error a.cs ").Path; var cmd = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { "b.cs" }); cmd.Arguments.Errors.Verify( // error CS2001: Source file 'System.Console.WriteLine(*?);' could not be found Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("System.Console.WriteLine(*?);")); AssertEx.Equal(new[] { "System.dll" }, cmd.Arguments.MetadataReferences.Select(r => r.Reference)); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "a.cs"), Path.Combine(WorkingDirectory, "b.cs") }, cmd.Arguments.SourceFiles.Select(file => file.Path)); CleanupAllGeneratedFiles(rsp); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void ResponseFiles_RelativePaths() { var parentDir = Temp.CreateDirectory(); var baseDir = parentDir.CreateDirectory("temp"); var dirX = baseDir.CreateDirectory("x"); var dirAB = baseDir.CreateDirectory("a b"); var dirSubDir = baseDir.CreateDirectory("subdir"); var dirGoo = parentDir.CreateDirectory("goo"); var dirBar = parentDir.CreateDirectory("bar"); string basePath = baseDir.Path; Func<string, string> prependBasePath = fileName => Path.Combine(basePath, fileName); var parser = new TestCommandLineParser(responseFiles: new Dictionary<string, string>() { { prependBasePath(@"a.rsp"), @" ""@subdir\b.rsp"" /r:..\v4.0.30319\System.dll /r:.\System.Data.dll a.cs @""..\c.rsp"" @\d.rsp /libpaths:..\goo;../bar;""a b"" " }, { Path.Combine(dirSubDir.Path, @"b.rsp"), @" b.cs " }, { prependBasePath(@"..\c.rsp"), @" c.cs /lib:x " }, { Path.Combine(Path.GetPathRoot(basePath), @"d.rsp"), @" # comment d.cs " } }, isInteractive: false); var args = parser.Parse(new[] { "first.cs", "second.cs", "@a.rsp", "last.cs" }, basePath, SdkDirectory); args.Errors.Verify(); Assert.False(args.IsScriptRunner); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); string[] references = args.MetadataReferences.Select(r => r.Reference).ToArray(); AssertEx.Equal(new[] { "first.cs", "second.cs", "b.cs", "a.cs", "c.cs", "d.cs", "last.cs" }.Select(prependBasePath), resolvedSourceFiles); AssertEx.Equal(new[] { typeof(object).Assembly.Location, @"..\v4.0.30319\System.dll", @".\System.Data.dll" }, references); AssertEx.Equal(new[] { RuntimeEnvironment.GetRuntimeDirectory() }.Concat(new[] { @"x", @"..\goo", @"../bar", @"a b" }.Select(prependBasePath)), args.ReferencePaths.ToArray()); Assert.Equal(basePath, args.BaseDirectory); } #nullable enable [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryNotAddedToKeyFileSearchPaths() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:web.config", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2021: File name 'web.config' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("web.config").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles_Wildcard() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:*", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2001: Source file '*' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("*").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } #nullable disable [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPath() { var parentDir = Temp.CreateDirectory(); var parser = CSharpCommandLineParser.Default.Parse(new[] { "file.cs", $"-out:{parentDir.Path}", "/noSdkPath" }, parentDir.Path, null); AssertEx.Equal(ImmutableArray<string>.Empty, parser.ReferencePaths); } [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPathReferenceSystemDll() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/nosdkpath", "/r:System.dll", "a.cs" }); var exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'System.dll' could not be found", outWriter.ToString().Trim()); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns() { var parser = new TestCommandLineParser( patterns: new Dictionary<string, string[]>() { { @"C:\temp|*.cs", new[] { "a.cs", "b.cs", "c.cs" } } }, recursivePatterns: new Dictionary<string, string[]>() { { @"C:\temp\a|*.cs", new[] { @"a\x.cs", @"a\b\b.cs", @"a\c.cs" } }, }); var args = parser.Parse(new[] { @"*.cs", @"/recurse:a\*.cs" }, @"C:\temp", SdkDirectory); args.Errors.Verify(); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { @"C:\temp\a.cs", @"C:\temp\b.cs", @"C:\temp\c.cs", @"C:\temp\a\x.cs", @"C:\temp\a\b\b.cs", @"C:\temp\a\c.cs" }, resolvedSourceFiles); } [Fact] public void ParseQuotedMainType() { // Verify the main switch are unquoted when used because of the issue with // MSBuild quoting some usages and not others. A quote character is not valid in either // these names. CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); args = DefaultParse(new[] { "/main:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); // Use of Cyrillic namespace args = DefaultParse(new[] { "/m:\"решения.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("решения.Class1", args.CompilationOptions.MainTypeName); } [Fact] [WorkItem(21508, "https://github.com/dotnet/roslyn/issues/21508")] public void ArgumentStartWithDashAndContainingSlash() { CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); args = DefaultParse(new[] { "-debug+/debug:portable" }, folder.Path); args.Errors.Verify( // error CS2007: Unrecognized option: '-debug+/debug:portable' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("-debug+/debug:portable").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); } [WorkItem(546009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546009")] [WorkItem(545991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545991")] [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns2() { var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); CreateFile(folder, "b.vb"); CreateFile(folder, "c.cpp"); var folderA = folder.CreateDirectory("A"); CreateFile(folderA, "A_a.cs"); CreateFile(folderA, "A_b.cs"); CreateFile(folderA, "A_c.vb"); var folderB = folder.CreateDirectory("B"); CreateFile(folderB, "B_a.cs"); CreateFile(folderB, "B_b.vb"); CreateFile(folderB, "B_c.cpx"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:. ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse: . ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:././.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); CSharpCommandLineArguments args; string[] resolvedSourceFiles; args = DefaultParse(new[] { @"/recurse:*.cp*", @"/recurse:a\*.c*", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { folder.Path + @"\c.cpp", folder.Path + @"\B\B_c.cpx", folder.Path + @"\a\A_a.cs", folder.Path + @"\a\A_b.cs", }, resolvedSourceFiles); args = DefaultParse(new[] { @"/recurse:.\\\\\\*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); args = DefaultParse(new[] { @"/recurse:.////*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFile_BadPath() { var args = DefaultParse(new[] { @"e:c:\test\test.cs", "/t:library" }, WorkingDirectory); Assert.Equal(3, args.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, args.Errors[0].Code); Assert.Equal((int)ErrorCode.WRN_NoSources, args.Errors[1].Code); Assert.Equal((int)ErrorCode.ERR_OutputNeedsName, args.Errors[2].Code); } private void CreateFile(TempDirectory folder, string file) { var f = folder.CreateFile(file); f.WriteAllText(""); } [Fact, WorkItem(546023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546023")] public void Win32ResourceArguments() { string[] args = new string[] { @"/win32manifest:..\here\there\everywhere\nonexistent" }; var parsedArgs = DefaultParse(args, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32manifest:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); } [Fact] public void Win32ResConflicts() { var parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32icon:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndIcon, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32manifest:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndManifest, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Icon: ", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:goo", "/noWin32Manifest", "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.True(parsedArgs.NoWin32Manifest); Assert.Null(parsedArgs.Win32Manifest); } [Fact] public void Win32ResInvalid() { var parsedArgs = DefaultParse(new[] { "/win32res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32res")); parsedArgs = DefaultParse(new[] { "/win32res+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32res+")); parsedArgs = DefaultParse(new[] { "/win32icon", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32icon")); parsedArgs = DefaultParse(new[] { "/win32icon+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32icon+")); parsedArgs = DefaultParse(new[] { "/win32manifest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32manifest")); parsedArgs = DefaultParse(new[] { "/win32manifest+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32manifest+")); } [Fact] public void Win32IconContainsGarbage() { string tmpFileName = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Path; var parsedArgs = DefaultParse(new[] { "/win32icon:" + tmpFileName, "a.cs" }, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_ErrorBuildingWin32Resources, errors.First().Code); Assert.Equal(1, errors.First().Arguments.Count()); CleanupAllGeneratedFiles(tmpFileName); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Win32ResQuotes() { string[] responseFile = new string[] { @" /win32res:d:\\""abc def""\a""b c""d\a.res", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.res", args.Win32ResourceFile); responseFile = new string[] { @" /win32icon:d:\\""abc def""\a""b c""d\a.ico", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.ico", args.Win32Icon); responseFile = new string[] { @" /win32manifest:d:\\""abc def""\a""b c""d\a.manifest", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.manifest", args.Win32Manifest); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseResources() { var diags = new List<Diagnostic>(); ResourceDescription desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\s""ome Fil""e.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"some File.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,""some Name"",public", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("some Name", desc.ResourceName); Assert.True(desc.IsPublic); // Use file name in place of missing resource name. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Quoted accessibility is fine. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,""private""", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Leading commas are not ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @",,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @", ,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // Trailing commas are ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private, ,", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName,publi", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("publi")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"D:rive\relative\path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"D:rive\relative\path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"inva\l*d?path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"inva\l*d?path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", (string)null, WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", "", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", " ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.True(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); var longE = new String('e', 1024); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("path,{0},private", longE), WorkingDirectory, diags, embedded: false); diags.Verify(); // Now checked during emit. diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal(longE, desc.ResourceName); Assert.False(desc.IsPublic); var longI = new String('i', 260); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("{0},e,private", longI), WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2021: File name 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii").WithLocation(1, 1)); } [Fact] public void ManagedResourceOptions() { CSharpCommandLineArguments parsedArgs; ResourceDescription resourceDescription; parsedArgs = DefaultParse(new[] { "/resource:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("a", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/res:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("b", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkresource:c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("c", resourceDescription.FileName); Assert.Equal("c", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkres:d", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("d", resourceDescription.FileName); Assert.Equal("d", resourceDescription.ResourceName); } [Fact] public void ManagedResourceOptions_SimpleErrors() { var parsedArgs = DefaultParse(new[] { "/resource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/resource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res")); parsedArgs = DefaultParse(new[] { "/RES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/RES+")); parsedArgs = DefaultParse(new[] { "/res-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res-:")); parsedArgs = DefaultParse(new[] { "/linkresource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkresource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkres", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres")); parsedArgs = DefaultParse(new[] { "/linkRES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkRES+")); parsedArgs = DefaultParse(new[] { "/linkres-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres-:")); } [Fact] public void Link_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/link:a", "/link:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Link: ,,, b ,,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/l:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/l:")); parsedArgs = DefaultParse(new[] { "/L", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/L")); parsedArgs = DefaultParse(new[] { "/l+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/l+")); parsedArgs = DefaultParse(new[] { "/link-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/link-:")); } [ConditionalFact(typeof(WindowsOnly))] public void Recurse_SimpleTests() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); var file2 = dir.CreateFile("b.cs"); var file3 = dir.CreateFile("c.txt"); var file4 = dir.CreateDirectory("d1").CreateFile("d.txt"); var file5 = dir.CreateDirectory("d2").CreateFile("e.cs"); file1.WriteAllText(""); file2.WriteAllText(""); file3.WriteAllText(""); file4.WriteAllText(""); file5.WriteAllText(""); var parsedArgs = DefaultParse(new[] { "/recurse:" + dir.ToString() + "\\*.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs", "{DIR}\\d2\\e.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "*.cs" }, dir.ToString()); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "/reCURSE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/reCURSE:")); parsedArgs = DefaultParse(new[] { "/RECURSE: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/RECURSE:")); parsedArgs = DefaultParse(new[] { "/recurse", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse")); parsedArgs = DefaultParse(new[] { "/recurse+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse+")); parsedArgs = DefaultParse(new[] { "/recurse-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse-:")); CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); CleanupAllGeneratedFiles(file3.Path); CleanupAllGeneratedFiles(file4.Path); CleanupAllGeneratedFiles(file5.Path); } [Fact] public void Reference_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/nostdlib", "/r:a", "/REFERENCE:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference: ,,, b ,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference:a=b,,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.MetadataReferences.Single().Properties.Aliases.Single()); Assert.Equal("b", parsedArgs.MetadataReferences.Single().Reference); parsedArgs = DefaultParse(new[] { "/r:a=b,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_OneAliasPerReference).WithArguments("b,,,c")); parsedArgs = DefaultParse(new[] { "/r:1=b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadExternIdentifier).WithArguments("1")); parsedArgs = DefaultParse(new[] { "/r:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/r:")); parsedArgs = DefaultParse(new[] { "/R", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/R")); parsedArgs = DefaultParse(new[] { "/reference+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference+")); parsedArgs = DefaultParse(new[] { "/reference-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference-:")); } [Fact] public void Target_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/target:exe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t")); parsedArgs = DefaultParse(new[] { "/target:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/target:xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/T+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+")); parsedArgs = DefaultParse(new[] { "/TARGET-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:")); } [Fact] public void Target_SimpleTestsNoSource() { var parsedArgs = DefaultParse(new[] { "/target:exe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/t' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:xyz" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/T+" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/T+' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/TARGET-:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/TARGET-:' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); } [Fact] public void ModuleManifest() { CSharpCommandLineArguments args = DefaultParse(new[] { "/win32manifest:blah", "/target:module", "a.cs" }, WorkingDirectory); args.Errors.Verify( // warning CS1927: Ignoring /win32manifest for module because it only applies to assemblies Diagnostic(ErrorCode.WRN_CantHaveManifestForModule)); // Illegal, but not clobbered. Assert.Equal("blah", args.Win32Manifest); } [Fact] public void ArgumentParsing() { var sdkDirectory = SdkDirectory; var parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b; c" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/help" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayLangVersions); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "//langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2001: Source file '//langversion:?' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("//langversion:?").WithLocation(1, 1) ); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version:something" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /langversion:6" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:-1", "c.csx", }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '-1' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("-1").WithLocation(1, 1)); Assert.False(parsedArgs.DisplayHelp); Assert.Equal(1, parsedArgs.SourceFiles.Length); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /r:s=d /r:d.dll" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "@roslyn_test_non_existing_file" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2011: Error opening response file 'D:\R0\Main\Binaries\Debug\dd' Diagnostic(ErrorCode.ERR_OpenResponseFile).WithArguments(Path.Combine(WorkingDirectory, @"roslyn_test_non_existing_file"))); Assert.False(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c /define:DEBUG" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\\" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r:d.dll", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/define:goo", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/define:goo' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/define:goo")); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\"/r d.dll\"" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r: d.dll", "a.cs" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); } [Theory] [InlineData("iso-1", LanguageVersion.CSharp1)] [InlineData("iso-2", LanguageVersion.CSharp2)] [InlineData("1", LanguageVersion.CSharp1)] [InlineData("1.0", LanguageVersion.CSharp1)] [InlineData("2", LanguageVersion.CSharp2)] [InlineData("2.0", LanguageVersion.CSharp2)] [InlineData("3", LanguageVersion.CSharp3)] [InlineData("3.0", LanguageVersion.CSharp3)] [InlineData("4", LanguageVersion.CSharp4)] [InlineData("4.0", LanguageVersion.CSharp4)] [InlineData("5", LanguageVersion.CSharp5)] [InlineData("5.0", LanguageVersion.CSharp5)] [InlineData("6", LanguageVersion.CSharp6)] [InlineData("6.0", LanguageVersion.CSharp6)] [InlineData("7", LanguageVersion.CSharp7)] [InlineData("7.0", LanguageVersion.CSharp7)] [InlineData("7.1", LanguageVersion.CSharp7_1)] [InlineData("7.2", LanguageVersion.CSharp7_2)] [InlineData("7.3", LanguageVersion.CSharp7_3)] [InlineData("8", LanguageVersion.CSharp8)] [InlineData("8.0", LanguageVersion.CSharp8)] [InlineData("9", LanguageVersion.CSharp9)] [InlineData("9.0", LanguageVersion.CSharp9)] [InlineData("preview", LanguageVersion.Preview)] public void LangVersion_CanParseCorrectVersions(string value, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); var scriptParsedArgs = ScriptParse(new[] { $"/langversion:{value}" }, WorkingDirectory); scriptParsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("6", "7", LanguageVersion.CSharp7)] [InlineData("7", "6", LanguageVersion.CSharp6)] [InlineData("7", "1", LanguageVersion.CSharp1)] [InlineData("6", "iso-1", LanguageVersion.CSharp1)] [InlineData("6", "iso-2", LanguageVersion.CSharp2)] [InlineData("6", "default", LanguageVersion.Default)] [InlineData("7", "default", LanguageVersion.Default)] [InlineData("iso-2", "6", LanguageVersion.CSharp6)] public void LangVersion_LatterVersionOverridesFormerOne(string formerValue, string latterValue, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{formerValue}", $"/langversion:{latterValue}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Fact] public void LangVersion_DefaultMapsCorrectly() { LanguageVersion defaultEffectiveVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Default, defaultEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:default", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(defaultEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_LatestMapsCorrectly() { LanguageVersion latestEffectiveVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Latest, latestEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:latest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Latest, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(latestEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_NoValueSpecified() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("iso-3")] [InlineData("iso1")] [InlineData("8.1")] [InlineData("10.1")] [InlineData("11")] [InlineData("1000")] public void LangVersion_BadVersion(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS1617: Invalid option 'XXX' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments(value).WithLocation(1, 1) ); } [Theory] [InlineData("0")] [InlineData("05")] [InlineData("07")] [InlineData("07.1")] [InlineData("08")] [InlineData("09")] public void LangVersion_LeadingZeroes(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS8303: Specified language version 'XXX' cannot have leading zeroes Diagnostic(ErrorCode.ERR_LanguageVersionCannotHaveLeadingZeroes).WithArguments(value).WithLocation(1, 1)); } [Theory] [InlineData("/langversion")] [InlineData("/langversion:")] [InlineData("/LANGversion:")] public void LangVersion_NoVersion(string option) { DefaultParse(new[] { option, "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/langversion:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/langversion:").WithLocation(1, 1)); } [Fact] public void LangVersion_LangVersions() { var args = DefaultParse(new[] { "/langversion:?" }, WorkingDirectory); args.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); Assert.True(args.DisplayLangVersions); } [Fact] public void LanguageVersionAdded_Canary() { // When a new version is added, this test will break. This list must be checked: // - update the "UpgradeProject" codefixer // - update all the tests that call this canary // - update MaxSupportedLangVersion (a relevant test should break when new version is introduced) // - email release management to add to the release notes (see old example: https://github.com/dotnet/core/pull/1454) AssertEx.SetEqual(new[] { "default", "1", "2", "3", "4", "5", "6", "7.0", "7.1", "7.2", "7.3", "8.0", "9.0", "10.0", "latest", "latestmajor", "preview" }, Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>().Select(v => v.ToDisplayString())); // For minor versions and new major versions, the format should be "x.y", such as "7.1" } [Fact] public void LanguageVersion_GetErrorCode() { var versions = Enum.GetValues(typeof(LanguageVersion)) .Cast<LanguageVersion>() .Except(new[] { LanguageVersion.Default, LanguageVersion.Latest, LanguageVersion.LatestMajor, LanguageVersion.Preview }) .Select(v => v.GetErrorCode()); var errorCodes = new[] { ErrorCode.ERR_FeatureNotAvailableInVersion1, ErrorCode.ERR_FeatureNotAvailableInVersion2, ErrorCode.ERR_FeatureNotAvailableInVersion3, ErrorCode.ERR_FeatureNotAvailableInVersion4, ErrorCode.ERR_FeatureNotAvailableInVersion5, ErrorCode.ERR_FeatureNotAvailableInVersion6, ErrorCode.ERR_FeatureNotAvailableInVersion7, ErrorCode.ERR_FeatureNotAvailableInVersion7_1, ErrorCode.ERR_FeatureNotAvailableInVersion7_2, ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ErrorCode.ERR_FeatureNotAvailableInVersion8, ErrorCode.ERR_FeatureNotAvailableInVersion9, ErrorCode.ERR_FeatureNotAvailableInVersion10, }; AssertEx.SetEqual(versions, errorCodes); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData(LanguageVersion.CSharp1, LanguageVersion.CSharp1), InlineData(LanguageVersion.CSharp2, LanguageVersion.CSharp2), InlineData(LanguageVersion.CSharp3, LanguageVersion.CSharp3), InlineData(LanguageVersion.CSharp4, LanguageVersion.CSharp4), InlineData(LanguageVersion.CSharp5, LanguageVersion.CSharp5), InlineData(LanguageVersion.CSharp6, LanguageVersion.CSharp6), InlineData(LanguageVersion.CSharp7, LanguageVersion.CSharp7), InlineData(LanguageVersion.CSharp7_1, LanguageVersion.CSharp7_1), InlineData(LanguageVersion.CSharp7_2, LanguageVersion.CSharp7_2), InlineData(LanguageVersion.CSharp7_3, LanguageVersion.CSharp7_3), InlineData(LanguageVersion.CSharp8, LanguageVersion.CSharp8), InlineData(LanguageVersion.CSharp9, LanguageVersion.CSharp9), InlineData(LanguageVersion.CSharp10, LanguageVersion.CSharp10), InlineData(LanguageVersion.CSharp10, LanguageVersion.LatestMajor), InlineData(LanguageVersion.CSharp10, LanguageVersion.Latest), InlineData(LanguageVersion.CSharp10, LanguageVersion.Default), InlineData(LanguageVersion.Preview, LanguageVersion.Preview), ] public void LanguageVersion_MapSpecifiedToEffectiveVersion(LanguageVersion expectedMappedVersion, LanguageVersion input) { Assert.Equal(expectedMappedVersion, input.MapSpecifiedToEffectiveVersion()); Assert.True(expectedMappedVersion.IsValid()); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData("iso-1", true, LanguageVersion.CSharp1), InlineData("ISO-1", true, LanguageVersion.CSharp1), InlineData("iso-2", true, LanguageVersion.CSharp2), InlineData("1", true, LanguageVersion.CSharp1), InlineData("1.0", true, LanguageVersion.CSharp1), InlineData("2", true, LanguageVersion.CSharp2), InlineData("2.0", true, LanguageVersion.CSharp2), InlineData("3", true, LanguageVersion.CSharp3), InlineData("3.0", true, LanguageVersion.CSharp3), InlineData("4", true, LanguageVersion.CSharp4), InlineData("4.0", true, LanguageVersion.CSharp4), InlineData("5", true, LanguageVersion.CSharp5), InlineData("5.0", true, LanguageVersion.CSharp5), InlineData("05", false, LanguageVersion.Default), InlineData("6", true, LanguageVersion.CSharp6), InlineData("6.0", true, LanguageVersion.CSharp6), InlineData("7", true, LanguageVersion.CSharp7), InlineData("7.0", true, LanguageVersion.CSharp7), InlineData("07", false, LanguageVersion.Default), InlineData("7.1", true, LanguageVersion.CSharp7_1), InlineData("7.2", true, LanguageVersion.CSharp7_2), InlineData("7.3", true, LanguageVersion.CSharp7_3), InlineData("8", true, LanguageVersion.CSharp8), InlineData("8.0", true, LanguageVersion.CSharp8), InlineData("9", true, LanguageVersion.CSharp9), InlineData("9.0", true, LanguageVersion.CSharp9), InlineData("10", true, LanguageVersion.CSharp10), InlineData("10.0", true, LanguageVersion.CSharp10), InlineData("08", false, LanguageVersion.Default), InlineData("07.1", false, LanguageVersion.Default), InlineData("default", true, LanguageVersion.Default), InlineData("latest", true, LanguageVersion.Latest), InlineData("latestmajor", true, LanguageVersion.LatestMajor), InlineData("preview", true, LanguageVersion.Preview), InlineData("latestpreview", false, LanguageVersion.Default), InlineData(null, true, LanguageVersion.Default), InlineData("bad", false, LanguageVersion.Default)] public void LanguageVersion_TryParseDisplayString(string input, bool success, LanguageVersion expected) { Assert.Equal(success, LanguageVersionFacts.TryParse(input, out var version)); Assert.Equal(expected, version); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Fact] public void LanguageVersion_TryParseTurkishDisplayString() { var originalCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR", useUserOverride: false); Assert.True(LanguageVersionFacts.TryParse("ISO-1", out var version)); Assert.Equal(LanguageVersion.CSharp1, version); Thread.CurrentThread.CurrentCulture = originalCulture; } [Fact] public void LangVersion_ListLangVersions() { var dir = Temp.CreateDirectory(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/langversion:?" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var expected = Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>() .Select(v => v.ToDisplayString()); var actual = outWriter.ToString(); var acceptableSurroundingChar = new[] { '\r', '\n', '(', ')', ' ' }; foreach (var version in expected) { if (version == "latest") continue; var foundIndex = actual.IndexOf(version); Assert.True(foundIndex > 0, $"Missing version '{version}'"); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex - 1]) >= 0); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex + version.Length]) >= 0); } } [Fact] [WorkItem(546961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546961")] public void Define() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;BAR,ZIP", "a.cs" }, WorkingDirectory); Assert.Equal(3, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("BAR", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("ZIP", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;4X", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.WRN_DefineIdentifierRequired, parsedArgs.Errors.First().Code); Assert.Equal("4X", parsedArgs.Errors.First().Arguments[0]); IEnumerable<Diagnostic> diagnostics; // The docs say /d:def1[;def2] string compliant = "def1;def2;def3"; var expected = new[] { "def1", "def2", "def3" }; var parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // Bug 17360: Dev11 allows for a terminating semicolon var dev11Compliant = "def1;def2;def3;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // And comma dev11Compliant = "def1,def2,def3,"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // This breaks everything var nonCompliant = "def1;;def2;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(nonCompliant, out diagnostics); diagnostics.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("")); Assert.Equal(new[] { "def1", "def2" }, parsed); // Bug 17360 parsedArgs = DefaultParse(new[] { "/d:public1;public2;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Fact] public void Debug() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:FULL", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.PortablePdb, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:PDBONLY", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "debug")); parsedArgs = DefaultParse(new[] { "/debug:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("+")); parsedArgs = DefaultParse(new[] { "/debug:invalid", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("invalid")); parsedArgs = DefaultParse(new[] { "/debug-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/debug-:")); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Pdb() { var parsedArgs = DefaultParse(new[] { "/pdb:something", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug:embedded", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.PdbPath); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb")); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb:", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb:")); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // temp: path changed //parsedArgs = DefaultParse(new[] { "/debug", "/pdb:.x", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); parsedArgs = DefaultParse(new[] { @"/pdb:""""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/pdb:""' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(@"/pdb:""""").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/pdb:C:\\", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("C:\\")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:C:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyPdb.pdb", parsedArgs.PdbPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:c:\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"c:\MyPdb.pdb", parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(Path.GetPathRoot(WorkingDirectory), @"MyFolder\MyPdb.pdb"), parsedArgs.PdbPath); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/pdb:""C:\My Folder\MyPdb.pdb""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyPdb.pdb", parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", WorkingDirectory), parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:..\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Temp: Path info changed // Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", "..\\", baseDirectory), parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b\OkFileName.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b\OkFileName.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\server\share\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\MyPdb.pdb", parsedArgs.PdbPath); // invalid name: parsedArgs = DefaultParse(new[] { "/pdb:a.b\0b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:a\uD800b.pdb", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.pdb")); Assert.Null(parsedArgs.PdbPath); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/pdb:""a<>.pdb""", "a.vb" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:.x", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.PdbPath); } [Fact] public void SourceLink() { var parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { @"/sourcelink:""s l.json""", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "s l.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); } [Fact] public void SourceLink_EndToEnd_EmbeddedPortable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:embedded", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var peStream = File.OpenRead(Path.Combine(dir.Path, "a.exe")); using (var peReader = new PEReader(peStream)) { var entry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); using (var mdProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Portable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:portable", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); using (var mdProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Windows() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); byte[] slContent = Encoding.UTF8.GetBytes(@"{ ""documents"" : {} }"); sl.WriteAllBytes(slContent); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:full", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); var actualData = PdbValidation.GetSourceLinkData(pdbStream); AssertEx.Equal(slContent, actualData); // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void Embed() { var parsedArgs = DefaultParse(new[] { "a.cs " }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Empty(parsedArgs.EmbeddedFiles); parsedArgs = DefaultParse(new[] { "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(parsedArgs.SourceFiles, parsedArgs.EmbeddedFiles); AssertEx.Equal( new[] { "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs", "/embed:b.cs", "/debug:embedded", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs;b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs,b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { @"/embed:""a,b.cs""", "/debug:portable", "a,b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a,b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); ; AssertEx.Equal( new[] { "a.txt", "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Theory] [InlineData("/debug:portable", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:portable", "/embed:embed.xyz", new[] { "embed.xyz" })] [InlineData("/debug:embedded", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:embedded", "/embed:embed.xyz", new[] { "embed.xyz" })] public void Embed_EndToEnd_Portable(string debugSwitch, string embedSwitch, string[] expectedEmbedded) { // embed.cs: large enough to compress, has #line directives const string embed_cs = @"/////////////////////////////////////////////////////////////////////////////// class Program { static void Main() { #line 1 ""embed.xyz"" System.Console.WriteLine(""Hello, World""); #line 3 System.Console.WriteLine(""Goodbye, World""); } } ///////////////////////////////////////////////////////////////////////////////"; // embed2.cs: small enough to not compress, no sequence points const string embed2_cs = @"class C { }"; // target of #line const string embed_xyz = @"print Hello, World print Goodbye, World"; Assert.True(embed_cs.Length >= EmbeddedText.CompressionThreshold); Assert.True(embed2_cs.Length < EmbeddedText.CompressionThreshold); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("embed.cs"); var src2 = dir.CreateFile("embed2.cs"); var txt = dir.CreateFile("embed.xyz"); src.WriteAllText(embed_cs); src2.WriteAllText(embed2_cs); txt.WriteAllText(embed_xyz); var expectedEmbeddedMap = new Dictionary<string, string>(); if (expectedEmbedded.Contains("embed.cs")) { expectedEmbeddedMap.Add(src.Path, embed_cs); } if (expectedEmbedded.Contains("embed2.cs")) { expectedEmbeddedMap.Add(src2.Path, embed2_cs); } if (expectedEmbedded.Contains("embed.xyz")) { expectedEmbeddedMap.Add(txt.Path, embed_xyz); } var output = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", debugSwitch, embedSwitch, "embed.cs", "embed2.cs" }); int exitCode = csc.Run(output); Assert.Equal("", output.ToString().Trim()); Assert.Equal(0, exitCode); switch (debugSwitch) { case "/debug:embedded": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: true); break; case "/debug:portable": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: false); break; case "/debug:full": ValidateEmbeddedSources_Windows(expectedEmbeddedMap, dir); break; } Assert.Empty(expectedEmbeddedMap); CleanupAllGeneratedFiles(src.Path); } private static void ValidateEmbeddedSources_Portable(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir, bool isEmbeddedPdb) { using (var peReader = new PEReader(File.OpenRead(Path.Combine(dir.Path, "embed.exe")))) { var entry = peReader.ReadDebugDirectory().SingleOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); Assert.Equal(isEmbeddedPdb, entry.DataSize > 0); using (var mdProvider = isEmbeddedPdb ? peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry) : MetadataReaderProvider.FromPortablePdbStream(File.OpenRead(Path.Combine(dir.Path, "embed.pdb")))) { var mdReader = mdProvider.GetMetadataReader(); foreach (var handle in mdReader.Documents) { var doc = mdReader.GetDocument(handle); var docPath = mdReader.GetString(doc.Name); SourceText embeddedSource = mdReader.GetEmbeddedSource(handle); if (embeddedSource == null) { continue; } Assert.Equal(expectedEmbeddedMap[docPath], embeddedSource.ToString()); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } } } private static void ValidateEmbeddedSources_Windows(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir) { ISymUnmanagedReader5 symReader = null; try { symReader = SymReaderFactory.CreateReader(File.OpenRead(Path.Combine(dir.Path, "embed.pdb"))); foreach (var doc in symReader.GetDocuments()) { var docPath = doc.GetName(); var sourceBlob = doc.GetEmbeddedSource(); if (sourceBlob.Array == null) { continue; } var sourceStr = Encoding.UTF8.GetString(sourceBlob.Array, sourceBlob.Offset, sourceBlob.Count); Assert.Equal(expectedEmbeddedMap[docPath], sourceStr); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } catch { symReader?.Dispose(); } } private static void ValidateWrittenSources(Dictionary<string, Dictionary<string, string>> expectedFilesMap, Encoding encoding = null) { foreach ((var dirPath, var fileMap) in expectedFilesMap.ToArray()) { foreach (var file in Directory.GetFiles(dirPath)) { var name = Path.GetFileName(file); var content = File.ReadAllText(file, encoding ?? Encoding.UTF8); Assert.Equal(fileMap[name], content); Assert.True(fileMap.Remove(name)); } Assert.Empty(fileMap); Assert.True(expectedFilesMap.Remove(dirPath)); } Assert.Empty(expectedFilesMap); } [Fact] public void Optimize() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(new CSharpCompilationOptions(OutputKind.ConsoleApplication).OptimizationLevel, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:+")); parsedArgs = DefaultParse(new[] { "/optimize:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:")); parsedArgs = DefaultParse(new[] { "/optimize-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize-:")); parsedArgs = DefaultParse(new[] { "/o-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "/optimize-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:+")); parsedArgs = DefaultParse(new string[] { "/o:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:")); parsedArgs = DefaultParse(new string[] { "/o-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o-:")); } [Fact] public void Deterministic() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); } [Fact] public void ParseReferences() { var parsedArgs = DefaultParse(new string[] { "/r:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); parsedArgs = DefaultParse(new string[] { "/r:goo.dll;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/l:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/addmodule:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/r:a=goo.dll", "/l:b=bar.dll", "/addmodule:c=mod.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(4, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "a" }), parsedArgs.MetadataReferences[1].Properties); Assert.Equal("bar.dll", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "b" }).WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[2].Properties); Assert.Equal("c=mod.dll", parsedArgs.MetadataReferences[3].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[3].Properties); // TODO: multiple files, quotes, etc. } [Fact] public void ParseAnalyzers() { var parsedArgs = DefaultParse(new string[] { @"/a:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/analyzer:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { "/analyzer:\"goo.dll\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:goo.dll;bar.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); Assert.Equal("bar.dll", parsedArgs.AnalyzerReferences[1].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/a:")); parsedArgs = DefaultParse(new string[] { "/a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/a")); } [Fact] public void Analyzers_Missing() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/a:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_Empty() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + typeof(object).Assembly.Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.DoesNotContain("warning", outWriter.ToString()); CleanupAllGeneratedFiles(file.Path); } private TempFile CreateRuleSetFile(string source) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); return file; } [Fact] public void RuleSetSwitchPositive() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1012")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1012"] == ReportDiagnostic.Error); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1013")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1013"] == ReportDiagnostic.Warn); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1014")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1014"] == ReportDiagnostic.Suppress); Assert.True(parsedArgs.CompilationOptions.GeneralDiagnosticOption == ReportDiagnostic.Warn); } [Fact] public void RuleSetSwitchQuoted() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + "\"" + file.Path + "\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); } [Fact] public void RuleSetSwitchParseErrors() { var parsedArgs = DefaultParse(new string[] { @"/ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah"), actual: parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah;blah.ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah;blah.ruleset"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah;blah.ruleset"), actual: parsedArgs.RuleSetPath); var file = CreateRuleSetFile("Random text"); parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(file.Path, "Data at the root level is invalid. Line 1, position 1.")); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); var err = parsedArgs.Errors.Single(); Assert.Equal((int)ErrorCode.ERR_CantReadRulesetFile, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal(file.Path, (string)err.Arguments[0]); var currentUICultureName = Thread.CurrentThread.CurrentUICulture.Name; if (currentUICultureName.Length == 0 || currentUICultureName.StartsWith("en", StringComparison.OrdinalIgnoreCase)) { Assert.Equal("Data at the root level is invalid. Line 1, position 1.", (string)err.Arguments[1]); } } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void Analyzers_Found() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic thrown Assert.True(outWriter.ToString().Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared")); // Diagnostic cannot be instantiated Assert.True(outWriter.ToString().Contains("warning CS8032")); CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_WithRuleSet() { string source = @" class C { int x; } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error. Assert.True(outWriter.ToString().Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared")); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warnaserror+", "/nowarn:8032" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warnaserror+", "/ruleset:" + ruleSetFile.Path, "/nowarn:8032" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Info); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test002", "/warnaserror-:Test002", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test002"], expected: ReportDiagnostic.Default); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesGeneralWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesSpecificWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_Capitalization() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:NullABLE", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_MultipleArguments() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable,Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 3, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void WarnAsError_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/warnaserror:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warn:0" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warn:0", "/ruleset:" + ruleSetFile.Path }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void DiagnosticFormatting() { string source = @" using System; class C { public static void Main() { Goo(0); #line 10 ""c:\temp\a\1.cs"" Goo(1); #line 20 ""C:\a\..\b.cs"" Goo(2); #line 30 ""C:\a\../B.cs"" Goo(3); #line 40 ""../b.cs"" Goo(4); #line 50 ""..\b.cs"" Goo(5); #line 60 ""C:\X.cs"" Goo(6); #line 70 ""C:\x.cs"" Goo(7); #line 90 "" "" Goo(9); #line 100 ""C:\*.cs"" Goo(10); #line 110 """" Goo(11); #line hidden Goo(12); #line default Goo(13); #line 140 ""***"" Goo(14); } } "; var dir = Temp.CreateDirectory(); dir.CreateFile("a.cs").WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // with /fullpaths off string expected = @" a.cs(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context a.cs(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); // with /fullpaths on outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/fullpaths", "a.cs" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); expected = @" " + Path.Combine(dir.Path, @"a.cs") + @"(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.Combine(dir.Path, @"a.cs") + @"(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); } [WorkItem(540891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540891")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseOut() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/out:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '' contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("")); parsedArgs = DefaultParse(new[] { @"/out:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out:")); parsedArgs = DefaultParse(new[] { @"/refout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/refout:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/refout:")); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/refonly", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8301: Do not use refout when using refonly. Diagnostic(ErrorCode.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly:incorrect", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/refonly:incorrect' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/refonly:incorrect").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refonly", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); // Dev11 reports CS2007: Unrecognized option: '/out' parsedArgs = DefaultParse(new[] { @"/out", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out")); parsedArgs = DefaultParse(new[] { @"/out+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/out+")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/out:C:\MyFolder\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\MyFolder", parsedArgs.OutputDirectory); Assert.Equal(@"C:\MyFolder\MyBinary.dll", parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/out:""C:\My Folder\MyBinary.dll""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\My Folder", parsedArgs.OutputDirectory); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.dll"), parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:..\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\abc\def", parsedArgs.OutputDirectory); // not specified: exe parsedArgs = DefaultParse(new[] { @"a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: dll parsedArgs = DefaultParse(new[] { @"/target:library", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.dll", parsedArgs.OutputFileName); Assert.Equal("a.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: module parsedArgs = DefaultParse(new[] { @"/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: appcontainerexe parsedArgs = DefaultParse(new[] { @"/target:appcontainerexe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: winmdobj parsedArgs = DefaultParse(new[] { @"/target:winmdobj", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.winmdobj", parsedArgs.OutputFileName); Assert.Equal("a.winmdobj", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { currentDrive + @":a.cs", "b.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.cs' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.cs")); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // UNC parsedArgs = DefaultParse(new[] { @"/out:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:\\server\share\file.exe", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share", parsedArgs.OutputDirectory); Assert.Equal("file.exe", parsedArgs.OutputFileName); Assert.Equal("file", parsedArgs.CompilationName); Assert.Equal("file.exe", parsedArgs.CompilationOptions.ModuleName); // invalid name: parsedArgs = DefaultParse(new[] { "/out:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); // Temporary skip following scenarios because of the error message changed (path) //parsedArgs = DefaultParse(new[] { "/out:a\uD800b.dll", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.dll")); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/out:""a<>.dll""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.dll")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", @"/out:.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", @"/out:.netmodule", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.netmodule' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".netmodule") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", ".cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(".netmodule", parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName); } [WorkItem(546012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546012")] [WorkItem(546007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546007")] [Fact] public void ParseOut2() { var parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); } [Fact] public void ParseInstrumentTestNames() { var parsedArgs = DefaultParse(SpecializedCollections.EmptyEnumerable<string>(), WorkingDirectory); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:""""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:", "Test.Flag.Name", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:None", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("None")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TestCoverage""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TESTCOVERAGE""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseDoc() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/doc:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); // NOTE: no colon in error message '/doc' parsedArgs = DefaultParse(new[] { @"/doc", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/doc+")); Assert.Null(parsedArgs.DocumentationPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/doc:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/doc:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/doc:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // UNC parsedArgs = DefaultParse(new[] { @"/doc:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // invalid name: parsedArgs = DefaultParse(new[] { "/doc:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // Temp // parsedArgs = DefaultParse(new[] { "/doc:a\uD800b.xml", "a.cs" }, baseDirectory); // parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.xml")); // Assert.Null(parsedArgs.DocumentationPath); // Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseErrorLog() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/errorlog:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Escaped quote in the middle is an error parsedArgs = DefaultParse(new[] { @"/errorlog:C:\""My Folder""\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"C:""My Folder\MyBinary.xml").WithLocation(1, 1)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/errorlog:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/errorlog:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // UNC parsedArgs = DefaultParse(new[] { @"/errorlog:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.ErrorLogOptions.Path); // invalid name: parsedArgs = DefaultParse(new[] { "/errorlog:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Parses SARIF version. parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml,version=2", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(SarifVersion.Sarif2, parsedArgs.ErrorLogOptions.SarifVersion); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Invalid SARIF version. string[] invalidSarifVersions = new string[] { @"C:\MyFolder\MyBinary.xml,version=1.0.0", @"C:\MyFolder\MyBinary.xml,version=2.1.0", @"C:\MyFolder\MyBinary.xml,version=42" }; foreach (string invalidSarifVersion in invalidSarifVersions) { parsedArgs = DefaultParse(new[] { $"/errorlog:{invalidSarifVersion}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(invalidSarifVersion, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } // Invalid errorlog qualifier. const string InvalidErrorLogQualifier = @"C:\MyFolder\MyBinary.xml,invalid=42"; parsedArgs = DefaultParse(new[] { $"/errorlog:{InvalidErrorLogQualifier}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,invalid=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(InvalidErrorLogQualifier, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Too many errorlog qualifiers. const string TooManyErrorLogQualifiers = @"C:\MyFolder\MyBinary.xml,version=2,version=2"; parsedArgs = DefaultParse(new[] { $"/errorlog:{TooManyErrorLogQualifiers}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=2,version=2' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(TooManyErrorLogQualifiers, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigParse() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/appconfig:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:a.exe.config", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a.exe.config", parsedArgs.AppConfigPath); // If ParseDoc succeeds, all other possible AppConfig paths should succeed as well -- they both call ParseGenericFilePath } [Fact] public void AppConfigBasic() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var appConfigFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>"); var silverlight = Temp.CreateFile().WriteAllBytes(ProprietaryTestResources.silverlight_v5_0_5_0.System_v5_0_5_0_silverlight).Path; var net4_0dll = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; // Test linking two appconfig dlls with simple src var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/r:" + silverlight, "/r:" + net4_0dll, "/appconfig:" + appConfigFile.Path, srcFile.Path }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(appConfigFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigBasicFail() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); string root = Path.GetPathRoot(srcDirectory); // Make sure we pick a drive that exists and is plugged in to avoid 'Drive not ready' var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/preferreduilang:en", $@"/appconfig:{root}DoesNotExist\NOwhere\bonobo.exe.config" , srcFile.Path }).Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal($@"error CS7093: Cannot read config file '{root}DoesNotExist\NOwhere\bonobo.exe.config' -- 'Could not find a part of the path '{root}DoesNotExist\NOwhere\bonobo.exe.config'.'", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void ParseDocAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and XML output. var parsedArgs = DefaultParse(new[] { @"/doc:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/doc:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [ConditionalFact(typeof(WindowsOnly))] public void ParseErrorLogAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and error log output. var parsedArgs = DefaultParse(new[] { @"/errorlog:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/errorlog:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [Fact] public void ModuleAssemblyName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:exe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); } [Fact] public void ModuleName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/modulename:bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("bar", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:CommonLanguageRuntimeLibrary", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("CommonLanguageRuntimeLibrary", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'modulename' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "modulename").WithLocation(1, 1) ); } [Fact] public void ModuleName001() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); file1.WriteAllText(@" class c1 { public static void Main(){} } "); var exeName = "aa.exe"; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/modulename:hocusPocus ", "/out:" + exeName + " ", file1.Path }); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, exeName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, "aa.exe")))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal("aa", peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal("hocusPocus", peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(exeName)) { System.IO.File.Delete(exeName); } CleanupAllGeneratedFiles(file1.Path); } [Fact] public void ParsePlatform() { var parsedArgs = DefaultParse(new[] { @"/platform:x64", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X64, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:X86", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X86, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:itanum", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadPlatformType, parsedArgs.Errors.First().Code); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:itanium", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Itanium, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu32bitpreferred", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:arm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Arm, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default parsedArgs = DefaultParse(new[] { "/platform:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform:")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default } [WorkItem(546016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546016")] [WorkItem(545997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545997")] [WorkItem(546019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546019")] [WorkItem(546029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546029")] [Fact] public void ParseBaseAddress() { var parsedArgs = DefaultParse(new[] { @"/baseaddress:x64", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(0x8000000000011111ul, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x86", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:-23", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:01777777777777777777777", "a.cs" }, WorkingDirectory); Assert.Equal(ulong.MaxValue, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x0000000100000000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0xffff8000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffffffff" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFFFFFF")); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x86", "/baseaddress:0xffff7fff" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x100000000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x10000000000000000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0x10000000000000000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); } [Fact] public void ParseFileAlignment() { var parsedArgs = DefaultParse(new[] { @"/filealign:x64", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number 'x64' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("x64")); parsedArgs = DefaultParse(new[] { @"/filealign:0x200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(0x200, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:512", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'filealign' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("filealign")); parsedArgs = DefaultParse(new[] { @"/filealign:-23", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '-23' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("-23")); parsedArgs = DefaultParse(new[] { @"/filealign:020000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '0' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("0")); parsedArgs = DefaultParse(new[] { @"/filealign:123", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '123' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("123")); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable() { var dir = Temp.CreateDirectory(); var lib1 = dir.CreateDirectory("lib1"); var lib2 = dir.CreateDirectory("lib2"); var lib3 = dir.CreateDirectory("lib3"); var sdkDirectory = SdkDirectory; var parsedArgs = DefaultParse(new[] { @"/lib:lib1", @"/libpath:lib2", @"/libpaths:lib3", "a.cs" }, dir.Path, sdkDirectory: sdkDirectory); AssertEx.Equal(new[] { sdkDirectory, lib1.Path, lib2.Path, lib3.Path }, parsedArgs.ReferencePaths); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable_Errors() { var parsedArgs = DefaultParse(new[] { @"/lib:c:lib2", @"/lib:o:\sdk1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'c:lib2' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"c:lib2", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path 'o:\sdk1' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\sdk1", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e:", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,.\Windows;e;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path '.\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@".\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:; ; ; ; ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("e:", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/lib+")); parsedArgs = DefaultParse(new[] { @"/lib: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); } [Fact, WorkItem(546005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546005")] public void SdkPathAndLibEnvVariable_Relative_csc() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var subDirectory = subFolder.ToString(); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, subDirectory, new[] { "/nologo", "/t:library", "/out:abc.xyz", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/lib:temp", "/r:abc.xyz", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } [Fact] public void UnableWriteOutput() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/out:" + subFolder.ToString(), src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.True(outWriter.ToString().Trim().StartsWith("error CS2012: Cannot open '" + subFolder.ToString() + "' for writing -- '", StringComparison.Ordinal)); // Cannot create a file when that file already exists. CleanupAllGeneratedFiles(src.Path); } [Fact] public void ParseHighEntropyVA() { var parsedArgs = DefaultParse(new[] { @"/highentropyva", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva+", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:-", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); //last one wins parsedArgs = DefaultParse(new[] { @"/highenTROPyva+", @"/HIGHentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); } [Fact] public void Checked() { var parsedArgs = DefaultParse(new[] { @"/checked+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checked:")); } [Fact] public void Nullable() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1)); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:eNable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disablE", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'Safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("Safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yeS", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yeS' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yeS").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:8" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:7.3" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:""safeonly""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\""enable\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '"enable"' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\"enable\"").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\disable\\", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\\disable\\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\\\disable\\\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\""enable\\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\enable\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\enable\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonlywarnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlywarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlywarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:SafeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'SafeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("SafeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:warnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Warnings' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:annotations", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); } [Fact] public void Usings() { CSharpCommandLineArguments parsedArgs; var sdkDirectory = SdkDirectory; parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar;Baz", "/using:System.Core;System" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar", "Baz", "System.Core", "System" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo;;Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo", "Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<namespace>' for '/u:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<namespace>", "/u:")); } [Fact] public void WarningsErrors() { var parsedArgs = DefaultParse(new string[] { "/nowarn", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); parsedArgs = DefaultParse(new string[] { "/nowarn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/nowarn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'warnaserror' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror")); parsedArgs = DefaultParse(new string[] { "/warnaserror:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:70000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror+:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror+:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror+")); parsedArgs = DefaultParse(new string[] { "/warnaserror-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror-:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror-")); parsedArgs = DefaultParse(new string[] { "/w", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/warn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warn:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/w:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/warn:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/warnaserror:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1;2;;3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } private static void AssertSpecificDiagnostics(int[] expectedCodes, ReportDiagnostic[] expectedOptions, CSharpCommandLineArguments args) { var actualOrdered = args.CompilationOptions.SpecificDiagnosticOptions.OrderBy(entry => entry.Key); AssertEx.Equal( expectedCodes.Select(i => MessageProvider.Instance.GetIdForErrorCode(i)), actualOrdered.Select(entry => entry.Key)); AssertEx.Equal(expectedOptions, actualOrdered.Select(entry => entry.Value)); } [Fact] public void WarningsParse() { var parsedArgs = DefaultParse(new string[] { "/warnaserror", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(0, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); parsedArgs = DefaultParse(new string[] { "/warnaserror:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:+1062,+1066,+1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1762,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics( new[] { 1062, 1066, 1734, 1762, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(4, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/w:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { @"/nowarn:""1062 1066 1734""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "/warnaserror:1066,1762", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:1066,1762", "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); } [Fact] public void AllowUnsafe() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/unsafe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/UNSAFE-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe-", "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); // default parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:")); parsedArgs = DefaultParse(new[] { "/unsafe:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:+")); parsedArgs = DefaultParse(new[] { "/unsafe-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe-:")); } [Fact] public void DelaySign() { CSharpCommandLineArguments parsedArgs; parsedArgs = DefaultParse(new[] { "/delaysign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/DELAYsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.False((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/delaysign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/delaysign:-")); Assert.Null(parsedArgs.CompilationOptions.DelaySign); } [Fact] public void PublicSign() { var parsedArgs = DefaultParse(new[] { "/publicsign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/PUBLICsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/publicsign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/publicsign:-").WithLocation(1, 1)); Assert.False(parsedArgs.CompilationOptions.PublicSign); } [WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")] [Fact] public void PublicSign_KeyFileRelativePath() { var parsedArgs = DefaultParse(new[] { "/publicsign", "/keyfile:test.snk", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "test.snk"), parsedArgs.CompilationOptions.CryptoKeyFile); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath() { DefaultParse(new[] { "/publicsign", "/keyfile:", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath2() { DefaultParse(new[] { "/publicsign", "/keyfile:\"\"", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [WorkItem(546301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546301")] [Fact] public void SubsystemVersionTests() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(4, 0), parsedArgs.EmitOptions.SubsystemVersion); // wrongly supported subsystem version. CompilationOptions data will be faithful to the user input. // It is normalized at the time of emit. parsedArgs = DefaultParse(new[] { "/subsystemversion:0.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:3.99", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(3, 99), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "/SUBsystemversion:5.333", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(5, 333), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/subsystemversion-")); parsedArgs = DefaultParse(new[] { "/subsystemversion: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion: 4.1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(" 4.1")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4 .0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4 .0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4. 0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4. 0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.2 ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.65536", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.65536")); parsedArgs = DefaultParse(new[] { "/subsystemversion:65536.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("65536.0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:-4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("-4.0")); // TODO: incompatibilities: versions lower than '6.2' and 'arm', 'winmdobj', 'appcontainer' } [Fact] public void MainType() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/m:A.B.C", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("A.B.C", parsedArgs.CompilationOptions.MainTypeName); parsedArgs = DefaultParse(new[] { "/m: ", "a.cs" }, WorkingDirectory); // Mimicking Dev11 parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); Assert.Null(parsedArgs.CompilationOptions.MainTypeName); // overriding the value parsedArgs = DefaultParse(new[] { "/m:A.B.C", "/MAIN:X.Y.Z", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("X.Y.Z", parsedArgs.CompilationOptions.MainTypeName); // error parsedArgs = DefaultParse(new[] { "/maiN:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "main")); parsedArgs = DefaultParse(new[] { "/MAIN+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/MAIN+")); parsedArgs = DefaultParse(new[] { "/M", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); // incompatible values /main && /target parsedArgs = DefaultParse(new[] { "/main:a", "/t:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); parsedArgs = DefaultParse(new[] { "/main:a", "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); } [Fact] public void Codepage() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/CodePage:1200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode", parsedArgs.Encoding.EncodingName); parsedArgs = DefaultParse(new[] { "/CodePage:1200", "/codePAGE:65001", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode (UTF-8)", parsedArgs.Encoding.EncodingName); // error parsedArgs = DefaultParse(new[] { "/codepage:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("0")); parsedArgs = DefaultParse(new[] { "/codepage:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("abc")); parsedArgs = DefaultParse(new[] { "/codepage:-5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("-5")); parsedArgs = DefaultParse(new[] { "/codepage: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "codepage")); parsedArgs = DefaultParse(new[] { "/codepage+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/codepage+")); } [Fact, WorkItem(24735, "https://github.com/dotnet/roslyn/issues/24735")] public void ChecksumAlgorithm() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sHa1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha1, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); // error parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("256")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha-1")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checksumAlgorithm+")); } [Fact] public void AddModule() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/addmodule:abc.netmodule", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.MetadataReferences.Length); Assert.Equal("abc.netmodule", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/aDDmodule:c:\\abc;c:\\abc;d:\\xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(3, parsedArgs.MetadataReferences.Length); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[1].Properties.Kind); Assert.Equal("d:\\xyz", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[2].Properties.Kind); // error parsedArgs = DefaultParse(new[] { "/ADDMODULE", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/addmodule:")); parsedArgs = DefaultParse(new[] { "/ADDMODULE+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/ADDMODULE+")); parsedArgs = DefaultParse(new[] { "/ADDMODULE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/ADDMODULE:")); } [Fact, WorkItem(530751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530751")] public void CS7061fromCS0647_ModuleWithCompilationRelaxations() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] public class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(4)] public class Mod { }").Path; string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] class Test { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source); // === Scenario 1 === var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); var parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Empty(outWriter.ToString()); // === Scenario 2 === outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source2 }).Run(outWriter); Assert.Equal(0, exitCode); modfile = source2.Substring(0, source2.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Equal(1, exitCode); // Dev11: CS0647 (Emit) Assert.Contains("error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(530780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530780")] public void AddModuleWithExtensionMethod() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"public static class Extensions { public static bool EB(this bool b) { return b; } }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source2 }).Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact, WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")] public void OLDCS0013FTL_MetadataEmitFailureSameModAndRes() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, "/linkres:" + modfile, source2 }).Run(outWriter); Assert.Equal(1, exitCode); // Native gives CS0013 at emit stage Assert.Equal("error CS7041: Each linked resource and module must have a unique filename. Filename '" + Path.GetFileName(modfile) + "' is specified more than once in this assembly", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact] public void Utf8Output() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output", "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/utf8output:")); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesRunnableProgram() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); string output = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.RunAndGetOutput("cmd.exe", $@"/C ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir) : ProcessUtilities.RunAndGetOutput("sh", $@"-c ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir); Assert.Equal("Hello World!", output.Trim()); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesLibrary() { var name = Guid.NewGuid().ToString() + ".dll"; string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public A Get() =^^^> default; ^ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public A Get\(\) =\> default\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); var assemblyName = AssemblyName.GetAssemblyName(Path.Combine(tempDir, name)); Assert.Equal(name.Replace(".dll", ", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), assemblyName.ToString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/55727")] public void CsiScript_WithSourceCodeRedirectedViaStandardInput_ExecutesNonInteractively() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo Console.WriteLine(""Hello World!"") | {s_CSharpScriptExecutable} -") : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo Console.WriteLine\(\\\""Hello World\!\\\""\) | {s_CSharpScriptExecutable} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); Assert.Equal("Hello World!", result.Output.Trim()); } [Fact] public void CscCompile_WithRedirectedInputIndicatorAndStandardInputNotRedirected_ReportsCS8782() { if (Console.IsInputRedirected) { // [applicable to both Windows and Unix] // if our parent (xunit) process itself has input redirected, we cannot test this // error case because our child process will inherit it and we cannot achieve what // we are aiming for: isatty(0):true and thereby Console.IsInputerRedirected:false in // child. running this case will make StreamReader to hang (waiting for input, that // we do not propagate: parent.In->child.In). // // note: in Unix we can "close" fd0 by appending `0>&-` in the `sh -c` command below, // but that will also not impact the result of isatty(), and in turn causes a different // compiler error. return; } string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir); Assert.True(result.ContainsErrors); Assert.Contains(((int)ErrorCode.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected).ToString(), result.Output); } [Fact] public void CscCompile_WithMultipleStdInOperators_WarnsCS2002() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -" .Replace(Environment.NewLine, string.Empty)) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.Contains(((int)ErrorCode.WRN_FileAlreadyIncluded).ToString(), result.Output); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_Off() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '?'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_On() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /utf8output /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '♚'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithModule() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:module /out:a.netmodule \"{aCs}\"", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /preferreduilang:en /t:module /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("warning CS2008: No source files specified.", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /resource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithLinkResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /linkresource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [Fact] public void KeyContainerAndKeyFile() { // KEYCONTAINER CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/keycontainer:RIPAdamYauch", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("RIPAdamYauch", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keycontainer-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keycontainer-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE parsedArgs = DefaultParse(new[] { @"/keyfile:\somepath\s""ome Fil""e.goo.bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); //EDMAURER let's not set the option in the event that there was an error. //Assert.Equal(@"\somepath\some File.goo.bar", parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyfile-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keyfile-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keyfile-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); // DEFAULTS parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE | KEYCONTAINER conflicts parsedArgs = DefaultParse(new[] { "/keyFile:a", "/keyContainer:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keyContainer:b", "/keyFile:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); } [Fact, WorkItem(554551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554551")] public void CS1698WRN_AssumedMatchThis() { // compile with: /target:library /keyfile:mykey.snk var text1 = @"[assembly:System.Reflection.AssemblyVersion(""2"")] public class CS1698_a {} "; // compile with: /target:library /reference:CS1698_a.dll /keyfile:mykey.snk var text2 = @"public class CS1698_b : CS1698_a {} "; //compile with: /target:library /out:cs1698_a.dll /reference:cs1698_b.dll /keyfile:mykey.snk var text = @"[assembly:System.Reflection.AssemblyVersion(""3"")] public class CS1698_c : CS1698_b {} public class CS1698_a {} "; var folder = Temp.CreateDirectory(); var cs1698a = folder.CreateFile("CS1698a.cs"); cs1698a.WriteAllText(text1); var cs1698b = folder.CreateFile("CS1698b.cs"); cs1698b.WriteAllText(text2); var cs1698 = folder.CreateFile("CS1698.cs"); cs1698.WriteAllText(text); var snkFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var kfile = "/keyfile:" + snkFile.Path; CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/t:library", kfile, "CS1698a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698a.Path, "CS1698b.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698b.Path, "/out:" + cs1698a.Path, "CS1698.cs" }, WorkingDirectory); // Roslyn no longer generates a warning for this...since this was only a warning, we're not really // saving anyone...does not provide high value to implement... // warning CS1698: Circular assembly reference 'CS1698a, Version=2.0.0.0, Culture=neutral,PublicKeyToken = 9e9d6755e7bb4c10' // does not match the output assembly name 'CS1698a, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10'. // Try adding a reference to 'CS1698a, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10' or changing the output assembly name to match. parsedArgs.Errors.Verify(); CleanupAllGeneratedFiles(snkFile.Path); CleanupAllGeneratedFiles(cs1698a.Path); CleanupAllGeneratedFiles(cs1698b.Path); CleanupAllGeneratedFiles(cs1698.Path); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30926")] public void BinaryFileErrorTest() { var binaryPath = Temp.CreateFile().WriteAllBytes(ResourcesNet451.mscorlib).Path; var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", binaryPath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( "error CS2015: '" + binaryPath + "' is a binary file instead of a text file", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(binaryPath); } #if !NETCOREAPP [WorkItem(530221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530221")] [WorkItem(5660, "https://github.com/dotnet/roslyn/issues/5660")] [ConditionalFact(typeof(WindowsOnly), typeof(IsEnglishLocal))] public void Bug15538() { // Several Jenkins VMs are still running with local systems permissions. This suite won't run properly // in that environment. Removing this check is being tracked by issue #79. using (var identity = System.Security.Principal.WindowsIdentity.GetCurrent()) { if (identity.IsSystem) { return; } // The icacls command fails on our Helix machines and it appears to be related to the use of the $ in // the username. // https://github.com/dotnet/roslyn/issues/28836 if (StringComparer.OrdinalIgnoreCase.Equals(Environment.UserDomainName, "WORKGROUP")) { return; } } var folder = Temp.CreateDirectory(); var source = folder.CreateFile("src.vb").WriteAllText("").Path; var _ref = folder.CreateFile("ref.dll").WriteAllText("").Path; try { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /inheritance:r /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + @" /deny %USERDOMAIN%\%USERNAME%:(r,WDAC) /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /r:" + _ref + " /t:library " + source, expectedRetCode: 1); Assert.Equal("error CS0009: Metadata file '" + _ref + "' could not be opened -- Access to the path '" + _ref + "' is denied.", output.Trim()); } finally { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /reset /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); File.Delete(_ref); } CleanupAllGeneratedFiles(source); } #endif [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="""" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileOrdering() { var rspFilePath1 = Temp.CreateFile().WriteAllText(@" /b /c ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d" }, new[] { "/a", @$"@""{rspFilePath1}""", "/d" }); var rspFilePath2 = Temp.CreateFile().WriteAllText(@" /c /d ").Path; rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b @""{rspFilePath2}"" ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", "/e" }); rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b ").Path; rspFilePath2 = Temp.CreateFile().WriteAllText(@" # this will be ignored /c /d ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", $@"@""{rspFilePath2}""", "/e" }); void assertOrder(string[] expected, string[] args) { var flattenedArgs = ArrayBuilder<string>.GetInstance(); var diagnostics = new List<Diagnostic>(); CSharpCommandLineParser.Default.FlattenArgs( args, diagnostics, flattenedArgs, scriptArgsOpt: null, baseDirectory: Path.DirectorySeparatorChar == '\\' ? @"c:\" : "/"); Assert.Empty(diagnostics); Assert.Equal(expected, flattenedArgs); flattenedArgs.Free(); } } [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference2() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="" "" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFile() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"" /d:""AA;BB"" /d:""N""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFileErr() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"""" /d:""AA;BB"" /d:""N"" ""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileSplitting() { string[] responseFile; responseFile = new string[] { @"a.cs b.cs ""c.cs e.cs""", @"hello world # this is a comment" }; IEnumerable<string> args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b.cs", @"c.cs e.cs", "hello", "world" }, args); // Check comment handling; comment character only counts at beginning of argument responseFile = new string[] { @" # ignore this", @" # ignore that ""hello""", @" a.cs #3.cs", @" b#.cs c#d.cs #e.cs", @" ""#f.cs""", @" ""#g.cs #h.cs""" }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b#.cs", "c#d.cs", "#f.cs", "#g.cs #h.cs" }, args); // Check backslash escaping responseFile = new string[] { @"a\b\c d\\e\\f\\ \\\g\\\h\\\i \\\\ \\\\\k\\\\\", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\b\c", @"d\\e\\f\\", @"\\\g\\\h\\\i", @"\\\\", @"\\\\\k\\\\\" }, args); // More backslash escaping and quoting responseFile = new string[] { @"a\""a b\\""b c\\\""c d\\\\""d e\\\\\""e f"" g""", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\""a", @"b\\""b c\\\""c d\\\\""d", @"e\\\\\""e", @"f"" g""" }, args); // Quoting inside argument is valid. responseFile = new string[] { @" /o:""goo.cs"" /o:""abc def""\baz ""/o:baz bar""bing", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"/o:""goo.cs""", @"/o:""abc def""\baz", @"""/o:baz bar""bing" }, args); } [ConditionalFact(typeof(WindowsOnly))] private void SourceFileQuoting() { string[] responseFile = new string[] { @"d:\\""abc def""\baz.cs ab""c d""e.cs", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); AssertEx.Equal(new[] { @"d:\abc def\baz.cs", @"c:\abc de.cs" }, args.SourceFiles.Select(file => file.Path)); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName1() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since DLL. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library" }, expectedOutputName: "p.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName2() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library", "/out:r.dll" }, expectedOutputName: "r.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName3() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName4() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName5() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:A" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName6() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:B" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName7() { string source1 = @" partial class A { static partial void Main() { } } "; string source2 = @" partial class A { static partial void Main(); } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName8() { string source1 = @" partial class A { static partial void Main(); } "; string source2 = @" partial class A { static partial void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName9() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since winmdobj. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:winmdobj" }, expectedOutputName: "p.winmdobj"); } [Fact] public void OutputFileName10() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since appcontainerexe. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:appcontainerexe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName_Switch() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [Fact] public void OutputFileName_NoEntryPoint() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal("error CS5001: Program does not contain a static 'Main' method suitable for an entry point", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact, WorkItem(1093063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1093063")] public void VerifyDiagnosticSeverityNotLocalized() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); // If "error" was localized, below assert will fail on PLOC builds. The output would be something like: "!pTCvB!vbc : !FLxft!error 表! CS5001:" Assert.Contains("error CS5001:", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(@"", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var patched = Regex.Replace(outWriter.ToString().Trim(), "version \\d+\\.\\d+\\.\\d+(-[\\w\\d]+)*", "version A.B.C-d"); patched = ReplaceCommitHash(patched); Assert.Equal(@" Microsoft (R) Visual C# Compiler version A.B.C-d (HASH) Copyright (C) Microsoft Corporation. All rights reserved.".Trim(), patched); CleanupAllGeneratedFiles(file.Path); } [Theory, InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (<developer build>)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (ABCDEF01)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (abcdef90)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (12345678)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)")] public void TestReplaceCommitHash(string orig, string expected) { Assert.Equal(expected, ReplaceCommitHash(orig)); } private static string ReplaceCommitHash(string s) { // open paren, followed by either <developer build> or 8 hex, followed by close paren return Regex.Replace(s, "(\\((<developer build>|[a-fA-F0-9]{8})\\))", "(HASH)"); } [Fact] public void ExtractShortCommitHash() { Assert.Null(CommonCompiler.ExtractShortCommitHash(null)); Assert.Equal("", CommonCompiler.ExtractShortCommitHash("")); Assert.Equal("<", CommonCompiler.ExtractShortCommitHash("<")); Assert.Equal("<developer build>", CommonCompiler.ExtractShortCommitHash("<developer build>")); Assert.Equal("1", CommonCompiler.ExtractShortCommitHash("1")); Assert.Equal("1234567", CommonCompiler.ExtractShortCommitHash("1234567")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("12345678")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("123456789")); } private void CheckOutputFileName(string source1, string source2, string inputName1, string inputName2, string[] commandLineArguments, string expectedOutputName) { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile(inputName1); file1.WriteAllText(source1); var file2 = dir.CreateFile(inputName2); file2.WriteAllText(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { inputName1, inputName2 }).ToArray()); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, "*" + PathUtilities.GetExtension(expectedOutputName)).Count()); Assert.Equal(1, Directory.EnumerateFiles(dir.Path, expectedOutputName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, expectedOutputName)))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(PathUtilities.RemoveExtension(expectedOutputName), peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(expectedOutputName, peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(expectedOutputName)) { System.IO.File.Delete(expectedOutputName); } CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); } [Fact] public void MissingReference() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/r:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_01() { string source = @" public class C { public static void Main() { } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect to be success, since there will be no warning) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:1 (expect success) // Note that even though the command line option has a warning, it is not going to become an error // in order to avoid the halt of compilation. exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror", "/nowarn:1" }); Assert.Equal(0, exitCode); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_02() { string source = @" public class C { public static void Main() { int x; // CS0168 } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect failure) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:168 (expect failure) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:168" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:219 (expect success) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:219" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:168 (expect success) exitCode = GetExitCode(source, "d.cs", new[] { "/warnaserror", "/nowarn:168" }); Assert.Equal(0, exitCode); } private int GetExitCode(string source, string fileName, string[] commandLineArguments) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { fileName }).ToArray()); int exitCode = csc.Run(outWriter); return exitCode; } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithNonExistingOutPath() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2012: Cannot open '" + dir.Path + "\\sub\\a.exe' for writing", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_01() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_02() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\ " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsDesktopOnly))] public void CompilationWithWrongOutPath_03() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:aaa:\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains(@"error CS2021: File name 'aaa:\a.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_04() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out: " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2005: Missing file specification for '/out:' option", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] public void EmittedSubsystemVersion() { var compilation = CSharpCompilation.Create("a.dll", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(subsystemVersion: SubsystemVersion.Create(5, 1)))); Assert.Equal(5, peHeaders.PEHeader.MajorSubsystemVersion); Assert.Equal(1, peHeaders.PEHeader.MinorSubsystemVersion); } [Fact] public void CreateCompilationWithKeyFile() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyfile:key.snk", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.IsType<DesktopStrongNameProvider>(comp.Options.StrongNameProvider); } [Fact] public void CreateCompilationWithKeyContainer() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keycontainer:bbb", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilationFallbackCommand() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyFile:key.snk", "/features:UseLegacyStrongNameProvider" }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilation_MainAndTargetIncompatibilities() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var compilation = CSharpCompilation.Create("a.dll", options: TestOptions.ReleaseDll); var options = compilation.Options; Assert.Equal(0, options.Errors.Length); options = options.WithMainTypeName("a"); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); var comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithOutputKind(OutputKind.WindowsApplication); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS1555: Could not find 'a' specified for Main method Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("a") ); options = options.WithOutputKind(OutputKind.NetModule); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithMainTypeName(null); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify(); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void SpecifyProperCodePage() { byte[] source = { 0x63, // c 0x6c, // l 0x61, // a 0x73, // s 0x73, // s 0x20, // 0xd0, 0x96, // Utf-8 Cyrillic character 0x7b, // { 0x7d, // } }; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllBytes(source); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:library \"{file}\"", startFolder: dir.Path); Assert.Equal("", output); // Autodetected UTF8, NO ERROR output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /preferreduilang:en /t:library /codepage:20127 \"{file}\"", expectedRetCode: 1, startFolder: dir.Path); // 20127: US-ASCII // 0xd0, 0x96 ==> ERROR Assert.Equal(@" a.cs(1,7): error CS1001: Identifier expected a.cs(1,7): error CS1514: { expected a.cs(1,7): error CS1513: } expected a.cs(1,7): error CS8803: Top-level statements must precede namespace and type declarations. a.cs(1,7): error CS1525: Invalid expression term '??' a.cs(1,9): error CS1525: Invalid expression term '{' a.cs(1,9): error CS1002: ; expected ".Trim(), Regex.Replace(output, "^.*a.cs", "a.cs", RegexOptions.Multiline).Trim()); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForDll() { var source = @" class C { } "; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForAppContainerExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsRuntimeApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinMD() { var source = @" class C { } "; CheckManifestString(source, OutputKind.WindowsRuntimeMetadata, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForModule() { var source = @" class C { } "; CheckManifestString(source, OutputKind.NetModule, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForExe() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var explicitManifestStream = new MemoryStream(Encoding.UTF8.GetBytes(explicitManifest)); var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest, expectedManifest); } // DLLs don't get the default manifest, but they do respect explicitly set manifests. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForDll() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest, expectedManifest); } // Modules don't have manifests, even if one is explicitly specified. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForModule() { var source = @" class C { } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; CheckManifestString(source, OutputKind.NetModule, explicitManifest, expectedManifest: null); } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeLibrary([In] IntPtr hFile); private void CheckManifestString(string source, OutputKind outputKind, string explicitManifest, string expectedManifest) { var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("Test.cs").WriteAllText(source); string outputFileName; string target; switch (outputKind) { case OutputKind.ConsoleApplication: outputFileName = "Test.exe"; target = "exe"; break; case OutputKind.WindowsApplication: outputFileName = "Test.exe"; target = "winexe"; break; case OutputKind.DynamicallyLinkedLibrary: outputFileName = "Test.dll"; target = "library"; break; case OutputKind.NetModule: outputFileName = "Test.netmodule"; target = "module"; break; case OutputKind.WindowsRuntimeMetadata: outputFileName = "Test.winmdobj"; target = "winmdobj"; break; case OutputKind.WindowsRuntimeApplication: outputFileName = "Test.exe"; target = "appcontainerexe"; break; default: throw TestExceptionUtilities.UnexpectedValue(outputKind); } MockCSharpCompiler csc; if (explicitManifest == null) { csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), Path.GetFileName(sourceFile.Path), }); } else { var manifestFile = dir.CreateFile("Test.config").WriteAllText(explicitManifest); csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), string.Format("/win32manifest:{0}", Path.GetFileName(manifestFile.Path)), Path.GetFileName(sourceFile.Path), }); } int actualExitCode = csc.Run(new StringWriter(CultureInfo.InvariantCulture)); Assert.Equal(0, actualExitCode); //Open as data IntPtr lib = LoadLibraryEx(Path.Combine(dir.Path, outputFileName), IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); const string resourceType = "#24"; var resourceId = outputKind == OutputKind.DynamicallyLinkedLibrary ? "#2" : "#1"; uint manifestSize; if (expectedManifest == null) { Assert.Throws<Win32Exception>(() => Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize)); } else { IntPtr manifestResourcePointer = Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize); string actualManifest = Win32Res.ManifestResourceToXml(manifestResourcePointer, manifestSize); Assert.Equal(expectedManifest, actualManifest); } FreeLibrary(lib); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_01() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { int x; // CS0168 } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /warnaserror ").Path; // Checks the base case without /noconfig (expect to see error) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/NOCONFIG", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "-noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_02() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_03() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /NOCONFIG ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_04() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" -noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact, WorkItem(530024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530024")] public void NoStdLib() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/nostdlib", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("{FILE}(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported", outWriter.ToString().Replace(Path.GetFileName(src.Path), "{FILE}").Trim()); // Bug#15021: breaking change - empty source no error with /nostdlib src.WriteAllText("namespace System { }"); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/langversion:8", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } private string GetDefaultResponseFilePath() { var cscRsp = global::TestResources.ResourceLoader.GetResourceBlob("csc.rsp"); return Temp.CreateFile().WriteAllBytes(cscRsp).Path; } [Fact, WorkItem(530359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530359")] public void NoStdLib02() { #region "source" var source = @" // <Title>A collection initializer can be declared with a user-defined IEnumerable that is declared in a user-defined System.Collections</Title> using System.Collections; class O<T> where T : new() { public T list = new T(); } class C { static StructCollection sc = new StructCollection { 1 }; public static int Main() { ClassCollection cc = new ClassCollection { 2 }; var o1 = new O<ClassCollection> { list = { 5 } }; var o2 = new O<StructCollection> { list = sc }; return 0; } } struct StructCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } class ClassCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } namespace System.Collections { public interface IEnumerable { void Add(int t); } } "; #endregion #region "mslib" var mslib = @" namespace System { public class Object {} public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct SByte { } public struct UInt32 { } public struct UInt64 { } public struct Char { } public struct Boolean { } public struct UInt16 { } public struct UIntPtr { } public struct IntPtr { } public class Delegate { } public class String { public int Length { get { return 10; } } } public class MulticastDelegate { } public class Array { } public class Exception { public Exception(string s){} } public class Type { } public class ValueType { } public class Enum { } public interface IEnumerable { } public interface IDisposable { } public class Attribute { } public class ParamArrayAttribute { } public struct Void { } public struct RuntimeFieldHandle { } public struct RuntimeTypeHandle { } public class Activator { public static T CreateInstance<T>(){return default(T);} } namespace Collections { public interface IEnumerator { } } namespace Runtime { namespace InteropServices { public class OutAttribute { } } namespace CompilerServices { public class RuntimeHelpers { } } } namespace Reflection { public class DefaultMemberAttribute { } } } "; #endregion var src = Temp.CreateFile("NoStdLib02.cs"); src.WriteAllText(source + mslib); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); string OriginalSource = src.Path; src = Temp.CreateFile("NoStdLib02b.cs"); src.WriteAllText(mslib); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(OriginalSource); CleanupAllGeneratedFiles(src.Path); } [Fact, WorkItem(546018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546018"), WorkItem(546020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546020"), WorkItem(546024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546024"), WorkItem(546049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546049")] public void InvalidDefineSwitch() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", src.ToString(), "/define" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:""""" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define: " }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,,," }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,blah,Blah" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a;;b@" }).Run(outWriter); Assert.Equal(0, exitCode); var errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", errorLines[0]); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", errorLines[1]); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a,b@;" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", outWriter.ToString().Trim()); //Bug 531612 - Native would normally not give the 2nd warning outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1", @"/d:TRACE=TRUE,DEBUG=TRUE" }).Run(outWriter); Assert.Equal(0, exitCode); errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1' is not a valid identifier", errorLines[0]); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'TRACE=TRUE' is not a valid identifier", errorLines[1]); CleanupAllGeneratedFiles(src.Path); } [WorkItem(733242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/733242")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug733242() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); using (var xmlFileHandle = File.Open(xml.ToString(), FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite)) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))); using (var reader = new StreamReader(xmlFileHandle)) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [WorkItem(768605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768605")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug768605() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC</summary> class C {} /// <summary>XYZ</summary> class E {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> <member name=""T:E""> <summary>XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } src.WriteAllText( @" /// <summary>ABC</summary> class C {} "); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> </members> </doc>".Trim(), content.Trim()); } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [Fact] public void ParseFullpaths() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths" }, WorkingDirectory); Assert.True(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); } [Fact] public void CheckFullpaths() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public static void Main() { string x; } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); // Checks the base case without /fullpaths (expect to see relative path name) // c:\temp> csc.exe c:\temp\a.cs // a.cs(6,16): warning CS0168: The variable 'x' is declared but never used var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see relative path name) // c:\temp> csc.exe c:\temp\example\a.cs // example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); Assert.DoesNotContain(source, outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /fullpaths (expect to see the full paths) // c:\temp> csc.exe c:\temp\a.cs /fullpaths // c:\temp\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/fullpaths", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + @"(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see the full path name) // c:\temp> csc.exe c:\temp\example\a.cs /fullpaths // c:\temp\example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs /fullpaths // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(source)), Path.GetFileName(source))); } [Fact] public void DefaultResponseFile() { var sdkDirectory = SdkDirectory; MockCSharpCompiler csc = new MockCSharpCompiler( GetDefaultResponseFilePath(), RuntimeUtilities.CreateBuildPaths(WorkingDirectory, sdkDirectory), new string[0]); AssertEx.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, "Accessibility.dll", "Microsoft.CSharp.dll", "System.Configuration.dll", "System.Configuration.Install.dll", "System.Core.dll", "System.Data.dll", "System.Data.DataSetExtensions.dll", "System.Data.Linq.dll", "System.Data.OracleClient.dll", "System.Deployment.dll", "System.Design.dll", "System.DirectoryServices.dll", "System.dll", "System.Drawing.Design.dll", "System.Drawing.dll", "System.EnterpriseServices.dll", "System.Management.dll", "System.Messaging.dll", "System.Runtime.Remoting.dll", "System.Runtime.Serialization.dll", "System.Runtime.Serialization.Formatters.Soap.dll", "System.Security.dll", "System.ServiceModel.dll", "System.ServiceModel.Web.dll", "System.ServiceProcess.dll", "System.Transactions.dll", "System.Web.dll", "System.Web.Extensions.Design.dll", "System.Web.Extensions.dll", "System.Web.Mobile.dll", "System.Web.RegularExpressions.dll", "System.Web.Services.dll", "System.Windows.Forms.dll", "System.Workflow.Activities.dll", "System.Workflow.ComponentModel.dll", "System.Workflow.Runtime.dll", "System.Xml.dll", "System.Xml.Linq.dll", }, StringComparer.OrdinalIgnoreCase); } [Fact] public void DefaultResponseFileNoConfig() { MockCSharpCompiler csc = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/noconfig" }); Assert.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, }, StringComparer.OrdinalIgnoreCase); } [Fact, WorkItem(545954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545954")] public void TestFilterParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" #pragma warning disable 440 using global = A; // CS0440 class A { static void Main() { #pragma warning suppress 440 } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(Path.GetFileName(source) + "(7,17): warning CS1634: Expected 'disable' or 'restore'", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/nowarn:1634", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", Path.Combine(baseDir, "nonexistent.cs"), source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2001: Source file '" + Path.Combine(baseDir, "nonexistent.cs") + "' could not be found.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546058")] public void TestNoWarnParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Test { static void Main() { //Generates warning CS1522: Empty switch block switch (1) { } //Generates warning CS0642: Possible mistaken empty statement while (false) ; { } } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1522,642", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(41610, "https://github.com/dotnet/roslyn/issues/41610")] public void TestWarnAsError_CS8632() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public string? field; public static void Main() { } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror:nullable", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(4,18): error CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546076")] public void TestWarnAsError_CS1522() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class Test { // CS0169 (level 3) private int x; // CS0109 (level 4) public new void Method() { } public static int Main() { int i = 5; // CS1522 (level 1) switch (i) { } return 0; // CS0162 (level 2) i = 6; } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(12,20): error CS1522: Empty switch block {fileName}(15,9): error CS0162: Unreachable code detected {fileName}(5,17): error CS0169: The field 'Test.x' is never used", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact(), WorkItem(546025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546025")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_01() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(TestResources.DiagnosticTests.badresfile).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Image is too small.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact(), WorkItem(217718, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=217718")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_02() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(new byte[] { 0, 0 }).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Unrecognized resource file format.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact, WorkItem(546114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546114")] public void TestFilterCommandLineDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class A { static void Main() { } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", "/out:goo.dll", "/nowarn:2008" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); System.IO.File.Delete(System.IO.Path.Combine(baseDir, "goo.dll")); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_Bug15905() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Program { #pragma warning disable 1998 public static void Main() { } #pragma warning restore 1998 } ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // Repro case 1 int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); // Repro case 2 exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1998", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ExistingPdb() { var dir = Temp.CreateDirectory(); var source1 = dir.CreateFile("program1.cs").WriteAllText(@" class " + new string('a', 10000) + @" { public static void Main() { } }"); var source2 = dir.CreateFile("program2.cs").WriteAllText(@" class Program2 { public static void Main() { } }"); var source3 = dir.CreateFile("program3.cs").WriteAllText(@" class Program3 { public static void Main() { } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int oldSize = 16 * 1024; var exe = dir.CreateFile("Program.exe"); using (var stream = File.OpenWrite(exe.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } var pdb = dir.CreateFile("Program.pdb"); using (var stream = File.OpenWrite(pdb.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } int exitCode1 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source1.Path }).Run(outWriter); Assert.NotEqual(0, exitCode1); ValidateZeroes(exe.Path, oldSize); ValidateZeroes(pdb.Path, oldSize); int exitCode2 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source2.Path }).Run(outWriter); Assert.Equal(0, exitCode2); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } Assert.True(new FileInfo(exe.Path).Length < oldSize); Assert.True(new FileInfo(pdb.Path).Length < oldSize); int exitCode3 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source3.Path }).Run(outWriter); Assert.Equal(0, exitCode3); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } } private static void ValidateZeroes(string path, int count) { using (var stream = File.OpenRead(path)) { byte[] buffer = new byte[count]; stream.Read(buffer, 0, buffer.Length); for (int i = 0; i < buffer.Length; i++) { if (buffer[i] != 0) { Assert.True(false); } } } } /// <summary> /// When the output file is open with <see cref="FileShare.Read"/> | <see cref="FileShare.Delete"/> /// the compiler should delete the file to unblock build while allowing the reader to continue /// reading the previous snapshot of the file content. /// /// On Windows we can read the original data directly from the stream without creating a memory map. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void FileShareDeleteCompatibility_Windows() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); var libPdb = dir.CreateFile("Lib.pdb").WriteAllText("PDB"); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/debug:full", libSrc.Path }).Run(outWriter); if (exitCode != 0) { AssertEx.AssertEqualToleratingWhitespaceDifferences("", outWriter.ToString()); } Assert.Equal(0, exitCode); AssertEx.Equal(new byte[] { 0x4D, 0x5A }, ReadBytes(libDll.Path, 2)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); AssertEx.Equal(new byte[] { 0x4D, 0x69 }, ReadBytes(libPdb.Path, 2)); AssertEx.Equal(new[] { (byte)'P', (byte)'D', (byte)'B' }, ReadBytes(fsPdb, 3)); fsDll.Dispose(); fsPdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } /// <summary> /// On Linux/Mac <see cref="FileShare.Delete"/> on its own doesn't do anything. /// We need to create the actual memory map. This works on Windows as well. /// </summary> [WorkItem(8896, "https://github.com/dotnet/roslyn/issues/8896")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void FileShareDeleteCompatibility_Xplat() { var bytes = TestResources.MetadataTests.InterfaceAndClass.CSClasses01; var mvid = ReadMvid(new MemoryStream(bytes)); var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllBytes(bytes); var libPdb = dir.CreateFile("Lib.pdb").WriteAllBytes(bytes); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var peDll = new PEReader(fsDll); var pePdb = new PEReader(fsPdb); // creates memory map view: var imageDll = peDll.GetEntireImage(); var imagePdb = pePdb.GetEntireImage(); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/target:library /debug:portable \"{libSrc.Path}\"", startFolder: dir.ToString()); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" Microsoft (R) Visual C# Compiler version {s_compilerVersion} Copyright (C) Microsoft Corporation. All rights reserved.", output); // reading original content from the memory map: Assert.Equal(mvid, ReadMvid(new MemoryStream(imageDll.GetContent().ToArray()))); Assert.Equal(mvid, ReadMvid(new MemoryStream(imagePdb.GetContent().ToArray()))); // reading original content directly from the streams: fsDll.Position = 0; fsPdb.Position = 0; Assert.Equal(mvid, ReadMvid(fsDll)); Assert.Equal(mvid, ReadMvid(fsPdb)); // reading new content from the file: using (var fsNewDll = File.OpenRead(libDll.Path)) { Assert.NotEqual(mvid, ReadMvid(fsNewDll)); } // Portable PDB metadata signature: AssertEx.Equal(new[] { (byte)'B', (byte)'S', (byte)'J', (byte)'B' }, ReadBytes(libPdb.Path, 4)); // dispose PEReaders (they dispose the underlying file streams) peDll.Dispose(); pePdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); // files can be deleted now: File.Delete(libSrc.Path); File.Delete(libDll.Path); File.Delete(libPdb.Path); // directory can be deleted (should be empty): Directory.Delete(dir.Path, recursive: false); } private static Guid ReadMvid(Stream stream) { using (var peReader = new PEReader(stream, PEStreamOptions.LeaveOpen)) { var mdReader = peReader.GetMetadataReader(); return mdReader.GetGuid(mdReader.GetModuleDefinition().Mvid); } } // Seems like File.SetAttributes(libDll.Path, FileAttributes.ReadOnly) doesn't restrict access to the file on Mac (Linux passes). [ConditionalFact(typeof(WindowsOnly)), WorkItem(8939, "https://github.com/dotnet/roslyn/issues/8939")] public void FileShareDeleteCompatibility_ReadOnlyFiles() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); File.SetAttributes(libDll.Path, FileAttributes.ReadOnly); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(libDll.Path, 3)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); fsDll.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } [Fact] public void FileShareDeleteCompatibility_ExistingDirectory() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateDirectory("Lib.dll"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); } private byte[] ReadBytes(Stream stream, int count) { var buffer = new byte[count]; stream.Read(buffer, 0, count); return buffer; } private byte[] ReadBytes(string path, int count) { using (var stream = File.OpenRead(path)) { return ReadBytes(stream, count); } } [Fact] public void IOFailure_DisposeOutputFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{exePath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposePdbFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var pdbPath = Path.ChangeExtension(exePath, "pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{pdbPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposeXmlFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var xmlPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/doc:{xmlPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{xmlPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Theory] [InlineData("portable")] [InlineData("full")] public void IOFailure_DisposeSourceLinkFile(string format) { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var sourceLinkPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.json"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug:" + format, $"/sourcelink:{sourceLinkPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == sourceLinkPath) { return new TestStream(backingStream: new MemoryStream(Encoding.UTF8.GetBytes(@" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } ")), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{sourceLinkPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_OpenOutputFile() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { throw new IOException(); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS2012: Cannot open '{exePath}' for writing", outWriter.ToString()); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenPdbFileNotCalled() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); string pdbPath = Path.ChangeExtension(exePath, ".pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/debug-", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { throw new IOException(); } return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(0, csc.Run(outWriter)); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); System.IO.File.Delete(pdbPath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenXmlFinal() { string sourcePath = MakeTrivialExe(); string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/doc:" + xmlPath, sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { throw new IOException(); } else { return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); } }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); var expectedOutput = string.Format("error CS0016: Could not write to output file '{0}' -- 'I/O error occurred.'", xmlPath); Assert.Equal(expectedOutput, outWriter.ToString().Trim()); Assert.NotEqual(0, exitCode); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); } private string MakeTrivialExe(string directory = null) { return Temp.CreateFile(directory: directory, prefix: "", extension: ".cs").WriteAllText(@" class Program { public static void Main() { } } ").Path; } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_AllErrorCodes() { const int jump = 200; for (int i = 0; i < 8000; i += (8000 / jump)) { int startErrorCode = (int)i * jump; int endErrorCode = startErrorCode + jump; string source = ComputeSourceText(startErrorCode, endErrorCode); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in a #pragma directive // (or via /nowarn /warnaserror flags on the command line). // Going forward, we won't generate any warning in such cases. This will make // maintenance of backwards compatibility easier (we no longer need to worry // about breaking existing projects / command lines if we deprecate / remove // an old warning code). Test(source, startErrorCode, endErrorCode); } } private static string ComputeSourceText(int startErrorCode, int endErrorCode) { string pragmaDisableWarnings = String.Empty; for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { string pragmaDisableStr = @"#pragma warning disable " + errorCode.ToString() + @" "; pragmaDisableWarnings += pragmaDisableStr; } return pragmaDisableWarnings + @" public class C { public static void Main() { } }"; } private void Test(string source, int startErrorCode, int endErrorCode) { string sourcePath = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(source).Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", sourcePath }).Run(outWriter); Assert.Equal(0, exitCode); var cscOutput = outWriter.ToString().Trim(); for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { Assert.True(cscOutput == string.Empty, "Failed at error code: " + errorCode); } CleanupAllGeneratedFiles(sourcePath); } [Fact] public void WriteXml() { var source = @" /// <summary> /// A subtype of <see cref=""object""/>. /// </summary> public class C { } "; var sourcePath = Temp.CreateFile(directory: WorkingDirectory, extension: ".cs").WriteAllText(source).Path; string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/target:library", "/out:Test.dll", "/doc:" + xmlPath, sourcePath }); var writer = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(writer); if (exitCode != 0) { Console.WriteLine(writer.ToString()); Assert.Equal(0, exitCode); } var bytes = File.ReadAllBytes(xmlPath); var actual = new string(Encoding.UTF8.GetChars(bytes)); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> A subtype of <see cref=""T:System.Object""/>. </summary> </member> </members> </doc> "; Assert.Equal(expected.Trim(), actual.Trim()); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); CleanupAllGeneratedFiles(xmlPath); } [WorkItem(546468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546468")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void CS2002WRN_FileAlreadyIncluded() { const string cs2002 = @"warning CS2002: Source file '{0}' specified multiple times"; TempDirectory tempParentDir = Temp.CreateDirectory(); TempDirectory tempDir = tempParentDir.CreateDirectory("tmpDir"); TempFile tempFile = tempDir.CreateFile("a.cs").WriteAllText(@"public class A { }"); // Simple case var commandLineArgs = new[] { "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times string aWrnString = String.Format(cs2002, "a.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, aWrnString); // Multiple duplicates commandLineArgs = new[] { "a.cs", "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times var warnings = new[] { aWrnString }; TestCS2002(commandLineArgs, tempDir.Path, 0, warnings); // Case-insensitive commandLineArgs = new[] { "a.cs", "A.cs" }; // warning CS2002: Source file 'A.cs' specified multiple times string AWrnString = String.Format(cs2002, "A.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, AWrnString); // Different extensions tempDir.CreateFile("a.csx"); commandLineArgs = new[] { "a.cs", "a.csx" }; // No errors or warnings TestCS2002(commandLineArgs, tempDir.Path, 0, String.Empty); // Absolute vs Relative commandLineArgs = new[] { @"tmpDir\a.cs", tempFile.Path }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times string tmpDiraString = String.Format(cs2002, @"tmpDir\a.cs"); TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Both relative commandLineArgs = new[] { @"tmpDir\..\tmpDir\a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // With wild cards commandLineArgs = new[] { tempFile.Path, @"tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // "/recurse" scenarios commandLineArgs = new[] { @"/recurse:a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); commandLineArgs = new[] { @"/recurse:a.cs", @"/recurse:tmpDir\..\tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Invalid file/path characters const string cs1504 = @"error CS1504: Source file '{0}' could not be opened -- {1}"; commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, "tmpDir\a.cs" }; // error CS1504: Source file '{0}' could not be opened: Illegal characters in path. var formattedcs1504Str = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, "tmpDir\a.cs"), "Illegal characters in path."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504Str); commandLineArgs = new[] { tempFile.Path, @"tmpDi\r*a?.cs" }; var parseDiags = new[] { // error CS2021: File name 'tmpDi\r*a?.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"tmpDi\r*a?.cs"), // error CS2001: Source file 'tmpDi\r*a?.cs' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments(@"tmpDi\r*a?.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); char currentDrive = Directory.GetCurrentDirectory()[0]; commandLineArgs = new[] { tempFile.Path, currentDrive + @":a.cs" }; parseDiags = new[] { // error CS2021: File name 'e:a.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + @":a.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, @":a.cs" }; // error CS1504: Source file '{0}' could not be opened: {1} var formattedcs1504 = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, @":a.cs"), @"The given path's format is not supported."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504); CleanupAllGeneratedFiles(tempFile.Path); System.IO.Directory.Delete(tempParentDir.Path, true); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string compileDiagnostic, params DiagnosticDescription[] parseDiagnostics) { TestCS2002(commandLineArgs, baseDirectory, expectedExitCode, new[] { compileDiagnostic }, parseDiagnostics); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string[] compileDiagnostics, params DiagnosticDescription[] parseDiagnostics) { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var allCommandLineArgs = new[] { "/nologo", "/preferreduilang:en", "/t:library" }.Concat(commandLineArgs).ToArray(); // Verify command line parser diagnostics. DefaultParse(allCommandLineArgs, baseDirectory).Errors.Verify(parseDiagnostics); // Verify compile. int exitCode = CreateCSharpCompiler(null, baseDirectory, allCommandLineArgs).Run(outWriter); Assert.Equal(expectedExitCode, exitCode); if (parseDiagnostics.IsEmpty()) { // Verify compile diagnostics. string outString = String.Empty; for (int i = 0; i < compileDiagnostics.Length; i++) { if (i != 0) { outString += @" "; } outString += compileDiagnostics[i]; } Assert.Equal(outString, outWriter.ToString().Trim()); } else { Assert.Null(compileDiagnostics); } } [Fact] public void ErrorLineEnd() { var tree = SyntaxFactory.ParseSyntaxTree("class C public { }", path: "goo"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/errorendlocation" }); var loc = new SourceLocation(tree.GetCompilationUnitRoot().FindToken(6)); var diag = new CSDiagnostic(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_MetadataNameTooLong), loc); var text = comp.DiagnosticFormatter.Format(diag); string stringStart = "goo(1,7,1,8)"; Assert.Equal(stringStart, text.Substring(0, stringStart.Length)); } [Fact] public void ReportAnalyzer() { var parsedArgs1 = DefaultParse(new[] { "a.cs", "/reportanalyzer" }, WorkingDirectory); Assert.True(parsedArgs1.ReportAnalyzer); var parsedArgs2 = DefaultParse(new[] { "a.cs", "" }, WorkingDirectory); Assert.False(parsedArgs2.ReportAnalyzer); } [Fact] public void ReportAnalyzerOutput() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains("WarningDiagnosticAnalyzer (Warning01)", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersParse() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/SKIPANALYZERS+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersSemantics(bool skipAnalyzers) { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var skipAnalyzersFlag = "/skipanalyzers" + (skipAnalyzers ? "+" : "-"); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { skipAnalyzersFlag, "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (skipAnalyzers) { Assert.DoesNotContain(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.DoesNotContain(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } else { Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(24835, "https://github.com/dotnet/roslyn/issues/24835")] public void TestCompilationSuccessIfOnlySuppressedDiagnostics() { var srcFile = Temp.CreateFile().WriteAllText(@" #pragma warning disable Warning01 class C { } "); var errorLog = Temp.CreateFile(); var csc = CreateCSharpCompiler( null, workingDirectory: Path.GetDirectoryName(srcFile.Path), args: new[] { "/errorlog:" + errorLog.Path, "/warnaserror+", "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new WarningDiagnosticAnalyzer())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); // Previously, the compiler would return error code 1 without printing any diagnostics Assert.Empty(outWriter.ToString()); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(errorLog.Path); } [Fact] [WorkItem(1759, "https://github.com/dotnet/roslyn/issues/1759")] public void AnalyzerDiagnosticThrowsInGetMessage() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerThatThrowsInGetMessage is reported, though it doesn't have the message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(3707, "https://github.com/dotnet/roslyn/issues/3707")] public void AnalyzerExceptionDiagnosticCanBeConfigured() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", $"/warnaserror:{AnalyzerExecutor.AnalyzerExceptionDiagnosticId}", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); var output = outWriter.ToString(); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(4589, "https://github.com/dotnet/roslyn/issues/4589")] public void AnalyzerReportsMisformattedDiagnostic() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerReportingMisformattedDiagnostic())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerReportingMisformattedDiagnostic is reported with the message format string, instead of the formatted message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.MessageFormat.ToString(CultureInfo.InvariantCulture), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void ErrorPathsFromLineDirectives() { string sampleProgram = @" #line 10 "".."" //relative path using System* "; var syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new string[] { }); var text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); //Pull off the last segment of the current directory. var expectedPath = Path.GetDirectoryName(WorkingDirectory); //the end of the diagnostic's "file" portion should be signaled with the '(' of the line/col info. Assert.Equal('(', text[expectedPath.Length]); sampleProgram = @" #line 10 "".>"" //invalid path character using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith(".>", StringComparison.Ordinal)); sampleProgram = @" #line 10 ""http://goo.bar/baz.aspx"" //URI using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith("http://goo.bar/baz.aspx", StringComparison.Ordinal)); } [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [Fact] public void PreferredUILang() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-US" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de-AT" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(531263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531263")] [Fact] public void EmptyFileName() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "" }).Run(outWriter); Assert.NotEqual(0, exitCode); // error CS2021: File name '' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Assert.Contains("CS2021", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void NoInfoDiagnostics() { string filePath = Temp.CreateFile().WriteAllText(@" using System.Diagnostics; // Unused. ").Path; var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(filePath); } [Fact] public void RuntimeMetadataVersion() { var parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:v4.0.30319" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("v4.0.30319", parsedArgs.EmitOptions.RuntimeMetadataVersion); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:-_+@%#*^" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("-_+@%#*^", parsedArgs.EmitOptions.RuntimeMetadataVersion); var comp = CreateEmptyCompilation(string.Empty); Assert.Equal("v4.0.30319", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "v4.0.30319"))).Module.MetadataVersion); comp = CreateEmptyCompilation(string.Empty); Assert.Equal("_+@%#*^", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "_+@%#*^"))).Module.MetadataVersion); } [WorkItem(715339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715339")] [ConditionalFact(typeof(WindowsOnly))] public void WRN_InvalidSearchPathDir() { var baseDir = Temp.CreateDirectory(); var sourceFile = baseDir.CreateFile("Source.cs"); var invalidPath = "::"; var nonExistentPath = "DoesNotExist"; // lib switch DefaultParse(new[] { "/lib:" + invalidPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path '::' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "/LIB option", "path is too long or invalid")); DefaultParse(new[] { "/lib:" + nonExistentPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "/LIB option", "directory does not exist")); // LIB environment variable DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: invalidPath).Errors.Verify( // warning CS1668: Invalid search path '::' specified in 'LIB environment variable' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "LIB environment variable", "path is too long or invalid")); DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: nonExistentPath).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in 'LIB environment variable' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "LIB environment variable", "directory does not exist")); CleanupAllGeneratedFiles(sourceFile.Path); } [WorkItem(650083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650083")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/55730")] public void ReservedDeviceNameAsFileName() { var parsedArgs = DefaultParse(new[] { "com9.cs", "/t:library " }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); parsedArgs = DefaultParse(new[] { "a.cs", "/t:library ", "/appconfig:.\\aux.config" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/out:com1.dll " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/doc:..\\lpt2.xml: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/debug+", "/pdb:.\\prn.pdb" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "@con.rsp" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_OpenResponseFile, parsedArgs.Errors.First().Code); } [Fact] public void ReservedDeviceNameAsFileName2() { string filePath = Temp.CreateFile().WriteAllText(@"class C {}").Path; // make sure reserved device names don't var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/r:com2.dll", "/target:library", "/preferreduilang:en", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file 'com2.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/link:..\\lpt8.dll", "/target:library", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file '..\\lpt8.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/lib:aux", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("warning CS1668: Invalid search path 'aux' specified in '/LIB option' -- 'directory does not exist'", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); } [Fact] public void ParseFeatures() { var args = DefaultParse(new[] { "/features:Test", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal("Test", args.ParseOptions.Features.Single().Key); args = DefaultParse(new[] { "/features:Test", "a.vb", "/Features:Experiment" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.ParseOptions.Features.Count); Assert.True(args.ParseOptions.Features.ContainsKey("Test")); Assert.True(args.ParseOptions.Features.ContainsKey("Experiment")); args = DefaultParse(new[] { "/features:Test=false,Key=value", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "false" }, { "Key", "value" } })); args = DefaultParse(new[] { "/features:Test,", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "true" } })); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseAdditionalFile() { var args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles.Single().Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:app.manifest" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:web.config" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:..\\web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\web.config"), args.AdditionalFiles.Single().Path); var baseDir = Temp.CreateDirectory(); baseDir.CreateFile("web1.config"); baseDir.CreateFile("web2.config"); baseDir.CreateFile("web3.config"); args = DefaultParse(new[] { "/additionalfile:web*.config", "a.cs" }, baseDir.Path); args.Errors.Verify(); Assert.Equal(3, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(baseDir.Path, "web1.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(baseDir.Path, "web2.config"), args.AdditionalFiles[1].Path); Assert.Equal(Path.Combine(baseDir.Path, "web3.config"), args.AdditionalFiles[2].Path); args = DefaultParse(new[] { "/additionalfile:web.config;app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { @"/additionalfile:""web.config,app.manifest""", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config,app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile:web.config:app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config:app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); args = DefaultParse(new[] { "/additionalfile:", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); } [Fact] public void ParseEditorConfig() { var args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:subdir\\.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:..\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\.editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig;subdir\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); args = DefaultParse(new[] { "/analyzerconfig:", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); } [Fact] public void NullablePublicOnly() { string source = @"namespace System.Runtime.CompilerServices { public sealed class NullableAttribute : Attribute { } // missing constructor } public class Program { private object? F = null; }"; string errorMessage = "error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'"; string filePath = Temp.CreateFile().WriteAllText(source).Path; int exitCode; string output; // No /feature (exitCode, output) = compileAndRun(featureOpt: null); Assert.Equal(1, exitCode); Assert.Contains(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly (exitCode, output) = compileAndRun("/features:nullablePublicOnly"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=true (exitCode, output) = compileAndRun("/features:nullablePublicOnly=true"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=false (the value is ignored) (exitCode, output) = compileAndRun("/features:nullablePublicOnly=false"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); (int, string) compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/langversion:8", "/nullable+", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return (exitCode, outWriter.ToString()); }; } // See also NullableContextTests.NullableAnalysisFlags_01(). [Fact] public void NullableAnalysisFlags() { string source = @"class Program { #nullable enable static object F1() => null; #nullable disable static object F2() => null; }"; string filePath = Temp.CreateFile().WriteAllText(source).Path; string fileName = Path.GetFileName(filePath); string[] expectedWarningsAll = new[] { fileName + "(4,27): warning CS8603: Possible null reference return." }; string[] expectedWarningsNone = Array.Empty<string>(); AssertEx.Equal(expectedWarningsAll, compileAndRun(featureOpt: null)); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=always")); AssertEx.Equal(expectedWarningsNone, compileAndRun("/features:run-nullable-analysis=never")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=ALWAYS")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=NEVER")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=true")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=false")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=unknown")); // unrecognized value ignored CleanupAllGeneratedFiles(filePath); string[] compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/nologo", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return outWriter.ToString().Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); }; } private static int OccurrenceCount(string source, string word) { var n = 0; var index = source.IndexOf(word, StringComparison.Ordinal); while (index >= 0) { ++n; index = source.IndexOf(word, index + word.Length, StringComparison.Ordinal); } return n; } private string VerifyOutput(TempDirectory sourceDir, TempFile sourceFile, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, int? expectedExitCode = null, bool errorlog = false, IEnumerable<ISourceGenerator> generators = null, params DiagnosticAnalyzer[] analyzers) { var args = new[] { "/nologo", "/preferreduilang:en", "/t:library", sourceFile.Path }; if (includeCurrentAssemblyAsAnalyzerReference) { args = args.Append("/a:" + Assembly.GetExecutingAssembly().Location); } if (errorlog) { args = args.Append("/errorlog:errorlog"); } if (additionalFlags != null) { args = args.Append(additionalFlags); } var csc = CreateCSharpCompiler(null, sourceDir.Path, args, analyzers: analyzers.ToImmutableArrayOrEmpty(), generators: generators.ToImmutableArrayOrEmpty()); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); var output = outWriter.ToString(); expectedExitCode ??= expectedErrorCount > 0 ? 1 : 0; Assert.True( expectedExitCode == exitCode, string.Format("Expected exit code to be '{0}' was '{1}'.{2} Output:{3}{4}", expectedExitCode, exitCode, Environment.NewLine, Environment.NewLine, output)); Assert.DoesNotContain("hidden", output, StringComparison.Ordinal); if (expectedInfoCount == 0) { Assert.DoesNotContain("info", output, StringComparison.Ordinal); } else { // Info diagnostics are only logged with /errorlog. Assert.True(errorlog); Assert.Equal(expectedInfoCount, OccurrenceCount(output, "info")); } if (expectedWarningCount == 0) { Assert.DoesNotContain("warning", output, StringComparison.Ordinal); } else { Assert.Equal(expectedWarningCount, OccurrenceCount(output, "warning")); } if (expectedErrorCount == 0) { Assert.DoesNotContain("error", output, StringComparison.Ordinal); } else { Assert.Equal(expectedErrorCount, OccurrenceCount(output, "error")); } return output; } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [Fact] public void NoWarnAndWarnAsError_AnalyzerDriverWarnings() { // This assembly has an abstract MockAbstractDiagnosticAnalyzer type which should cause // compiler warning CS8032 to be produced when compilations created in this test try to load it. string source = @"using System;"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:CS8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be promoted to an error via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:8032" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_HiddenDiagnostic() { // This assembly has a HiddenDiagnosticAnalyzer type which should produce custom hidden // diagnostics for #region directives present in the compilations created in this test. var source = @"using System; #region Region #endregion"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /nowarn: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror+ has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warnaserror- has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror: promotes custom hidden diagnostic Hidden01 to an error. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror-: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Hidden01" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Hidden01", "/nowarn:8032" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Hidden01", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void NoWarnAndWarnAsError_InfoDiagnostic(bool errorlog) { // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. // This assembly has an InfoDiagnosticAnalyzer type which should produce custom info // diagnostics for the #pragma warning restore directives present in the compilations created in this test. var source = @"using System; #pragma warning restore"; var name = "a.cs"; string output; output = GetOutput(name, source, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 suppresses custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0" }, errorlog: errorlog); // TEST: Verify that custom info diagnostic Info01 can be individually suppressed via /nowarn:. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can never be promoted to an error via /warnaserror+. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when /warnaserror- is used. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can be individually promoted to an error via /warnaserror:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when passed to /warnaserror-:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0", "/warnaserror:Info01" }, errorlog: errorlog); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/warn:0" }); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Info01", "/nowarn:8032" }, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Info01", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); } private string GetOutput( string name, string source, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, bool errorlog = false) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(name); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference, additionalFlags, expectedInfoCount, expectedWarningCount, expectedErrorCount, null, errorlog); CleanupAllGeneratedFiles(file.Path); return output; } [WorkItem(11368, "https://github.com/dotnet/roslyn/issues/11368")] [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(998069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998069")] [WorkItem(998724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998724")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_WarningDiagnostic() { // This assembly has a WarningDiagnosticAnalyzer type which should produce custom warning // diagnostics for source types present in the compilations created in this test. string source = @" class C { static void Main() { int i; } } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 3); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:cs0168,warning01,700000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror- keeps compiler warning CS0168 as well as custom warning diagnostic Warning01 as warnings. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 can be individually promoted to an error via /warnaserror+:. // This doesn't work correctly currently - promoting compiler warning CS0168 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069). output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:CS0168" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:cs0168,warning01,58000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 as well as compiler warning CS0168 can be promoted to errors via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:CS0168,Warning01" }, expectedWarningCount: 1, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror+" }); // TEST: Verify that /warn:0 overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror-" }); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror-:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror+" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror-" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Something,CS0168,Warning01" }); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Warning01", "/warnaserror-:Warning01" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,CS0168,58000,8032", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-:Warning01,CS0168,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,CS0168,58000", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror+:Warning01,CS0168,58000" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Warning01,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_ErrorDiagnostic() { // This assembly has an ErrorDiagnosticAnalyzer type which should produce custom error // diagnostics for #pragma warning disable directives present in the compilations created in this test. string source = @"using System; #pragma warning disable"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:Error01" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror+:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when custom error diagnostic Error01 is present. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes custom error diagnostic Error01 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_CompilerErrorDiagnostic() { string source = @"using System; class C { static void Main() { int i = new Exception(); } }"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /nowarn:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when compiler error CS0029 is present. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes compiler error CS0029 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror:0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins1() { var arguments = DefaultParse(new[] { "/warnaserror-:3001", "/warnaserror" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(true)); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins2() { var arguments = DefaultParse(new[] { "/warnaserror", "/warnaserror-:3001" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(false)); } [WorkItem(1091972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091972")] [WorkItem(444, "CodePlex")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug1091972() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C { static void Main() { var textStreamReader = new System.IO.StreamReader(typeof(C).Assembly.GetManifestResourceStream(""doc.xml"")); System.Console.WriteLine(textStreamReader.ReadToEnd()); } } "); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /doc:doc.xml /out:out.exe /resource:doc.xml \"{0}\"", src.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml"))); var expected = @"<?xml version=""1.0""?> <doc> <assembly> <name>out</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(); using (var reader = new StreamReader(Path.Combine(dir.ToString(), "doc.xml"))) { var content = reader.ReadToEnd(); Assert.Equal(expected, content.Trim()); } output = ProcessUtilities.RunAndGetOutput(Path.Combine(dir.ToString(), "out.exe"), startFolder: dir.ToString()); Assert.Equal(expected, output.Trim()); CleanupAllGeneratedFiles(src.Path); } [ConditionalFact(typeof(WindowsOnly))] public void CommandLineMisc() { CSharpCommandLineArguments args = null; string baseDirectory = @"c:\test"; Func<string, CSharpCommandLineArguments> parse = (x) => FullParse(x, baseDirectory); args = parse(@"/out:""a.exe"""); Assert.Equal(@"a.exe", args.OutputFileName); args = parse(@"/pdb:""a.pdb"""); Assert.Equal(Path.Combine(baseDirectory, @"a.pdb"), args.PdbPath); // The \ here causes " to be treated as a quote, not as an escaping construct args = parse(@"a\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a""b", @"c:\test\c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"a\\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a\b c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"/nostdlib /r:""a.dll"",""b.dll"" c.cs"); Assert.Equal( new[] { @"a.dll", @"b.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a-s.dll"",""b-s.dll"" c.cs"); Assert.Equal( new[] { @"a-s.dll", @"b-s.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a,;s.dll"",""b,;s.dll"" c.cs"); Assert.Equal( new[] { @"a,;s.dll", @"b,;s.dll" }, args.MetadataReferences.Select(x => x.Reference)); } [Fact] public void CommandLine_ScriptRunner1() { var args = ScriptParse(new[] { "--", "script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "@script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "@script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "-script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "-script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "--", "--" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "--") }, args.SourceFiles.Select(f => f.Path)); Assert.True(args.SourceFiles[0].IsScript); AssertEx.Equal(new[] { "--" }, args.ScriptArguments); // TODO: fails on Linux (https://github.com/dotnet/roslyn/issues/5904) // Result: C:\/script.csx //args = ScriptParse(new[] { "-i", "script.csx", "--", "--" }, baseDirectory: @"C:\"); //Assert.True(args.InteractiveMode); //AssertEx.Equal(new[] { @"C:\script.csx" }, args.SourceFiles.Select(f => f.Path)); //Assert.True(args.SourceFiles[0].IsScript); //AssertEx.Equal(new[] { "--" }, args.ScriptArguments); } [WorkItem(127403, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/127403")] [Fact] public void ParseSeparatedPaths_QuotedComma() { var paths = CSharpCommandLineParser.ParseSeparatedPaths(@"""a, b"""); Assert.Equal( new[] { @"a, b" }, paths); } [Fact] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapParser() { var s = PathUtilities.DirectorySeparatorStr; var parsedArgs = DefaultParse(new[] { "/pathmap:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { $"/pathmap:abc{s}=/", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("abc" + s, "/"), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1,K2=V2", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K2" + s, "V2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:,,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=,=v", "a.cs" }, WorkingDirectory); Assert.Equal(2, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[1].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=v=bad", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:=v", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:\"supporting spaces=is hard\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("supporting spaces" + s, "is hard" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1=V 1\",\"K 2=V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1\"=\"V 1\",\"K 2\"=\"V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"a ==,,b\"=\"1,,== 2\",\"x ==,,y\"=\"3 4\",", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("a =,b" + s, "1,= 2" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("x =,y" + s, "3 4" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { @"/pathmap:C:\temp\=/_1/,C:\temp\a\=/_2/,C:\temp\a\b\=/_3/", "a.cs", @"a\b.cs", @"a\b\c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\b\", "/_3/"), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\", "/_2/"), parsedArgs.PathMap[1]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\", "/_1/"), parsedArgs.PathMap[2]); } [Theory] [InlineData("", new string[0])] [InlineData(",", new[] { "", "" })] [InlineData(",,", new[] { "," })] [InlineData(",,,", new[] { ",", "" })] [InlineData(",,,,", new[] { ",," })] [InlineData("a,", new[] { "a", "" })] [InlineData("a,b", new[] { "a", "b" })] [InlineData(",,a,,,,,b,,", new[] { ",a,,", "b," })] public void SplitWithDoubledSeparatorEscaping(string str, string[] expected) { AssertEx.Equal(expected, CommandLineParser.SplitWithDoubledSeparatorEscaping(str, ',')); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbParser() { var dir = Path.Combine(WorkingDirectory, "a"); var parsedArgs = DefaultParse(new[] { $@"/pathmap:{dir}=b:\", "a.cs", @"/pdb:a\data.pdb", "/debug:full" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(dir, @"data.pdb"), parsedArgs.PdbPath); // This value is calculate during Emit phases and should be null even in the face of a pathmap targeting it. Assert.Null(parsedArgs.EmitOptions.PdbFilePath); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbEmit() { void AssertPdbEmit(TempDirectory dir, string pdbPath, string pePdbPath, params string[] extraArgs) { var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var defaultArgs = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug:full", $"/pdb:{pdbPath}" }; var isDeterministic = extraArgs.Contains("/deterministic"); var args = defaultArgs.Concat(extraArgs).ToArray(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); Assert.True(File.Exists(pdbPath)); using (var peStream = File.OpenRead(exePath)) { PdbValidation.ValidateDebugDirectory(peStream, null, pePdbPath, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic); } } // Case with no mappings using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, pdbPath); } // Simple mapping using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Simple mapping deterministic using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\", "/deterministic"); } // Partial mapping using (var dir = new DisposableDirectory(Temp)) { dir.CreateDirectory("pdb"); var pdbPath = Path.Combine(dir.Path, @"pdb\a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\pdb\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Legacy feature flag using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"a.pdb", $@"/features:pdb-path-determinism"); } // Unix path map using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"/a.pdb", $@"/pathmap:{dir.Path}=/"); } // Multi-specified path map with mixed slashes using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, "/goo/a.pdb", $"/pathmap:{dir.Path}=/goo,{dir.Path}{PathUtilities.DirectorySeparatorChar}=/bar"); } } [CompilerTrait(CompilerFeature.Determinism)] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void DeterministicPdbsRegardlessOfBitness() { var dir = Temp.CreateDirectory(); var dir32 = dir.CreateDirectory("32"); var dir64 = dir.CreateDirectory("64"); var programExe32 = dir32.CreateFile("Program.exe"); var programPdb32 = dir32.CreateFile("Program.pdb"); var programExe64 = dir64.CreateFile("Program.exe"); var programPdb64 = dir64.CreateFile("Program.pdb"); var sourceFile = dir.CreateFile("Source.cs").WriteAllText(@" using System; using System.Linq; using System.Collections.Generic; namespace N { using I4 = System.Int32; class Program { public static IEnumerable<int> F() { I4 x = 1; yield return 1; yield return x; } public static void Main(string[] args) { dynamic x = 1; const int a = 1; F().ToArray(); Console.WriteLine(x + a); } } }"); var csc32src = $@" using System; using System.Reflection; class Runner {{ static int Main(string[] args) {{ var assembly = Assembly.LoadFrom(@""{s_CSharpCompilerExecutable}""); var program = assembly.GetType(""Microsoft.CodeAnalysis.CSharp.CommandLine.Program""); var main = program.GetMethod(""Main""); return (int)main.Invoke(null, new object[] {{ args }}); }} }} "; var csc32 = CreateCompilationWithMscorlib46(csc32src, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86), assemblyName: "csc32"); var csc32exe = dir.CreateFile("csc32.exe").WriteAllBytes(csc32.EmitToArray()); dir.CopyFile(Path.ChangeExtension(s_CSharpCompilerExecutable, ".exe.config"), "csc32.exe.config"); dir.CopyFile(Path.Combine(Path.GetDirectoryName(s_CSharpCompilerExecutable), "csc.rsp")); var output = ProcessUtilities.RunAndGetOutput(csc32exe.Path, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir32.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir32.Path); Assert.Equal("", output); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir64.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir64.Path); Assert.Equal("", output); AssertEx.Equal(programExe32.ReadAllBytes(), programExe64.ReadAllBytes()); AssertEx.Equal(programPdb32.ReadAllBytes(), programPdb64.ReadAllBytes()); } [WorkItem(7588, "https://github.com/dotnet/roslyn/issues/7588")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Version() { var folderName = Temp.CreateDirectory().ToString(); var argss = new[] { "/version", "a.cs /version /preferreduilang:en", "/version /nologo", "/version /help", }; foreach (var args in argss) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, args, startFolder: folderName); Assert.Equal(s_compilerVersion, output.Trim()); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RefOut() { var dir = Temp.CreateDirectory(); var refDir = dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" public class C { /// <summary>Main method</summary> public static void Main() { System.Console.Write(""Hello""); } /// <summary>Private method</summary> private static void PrivateMethod() { System.Console.Write(""Private""); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.exe", "/refout:ref/a.dll", "/doc:doc.xml", "/deterministic", "/langversion:7", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exe = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exe)); MetadataReaderUtils.VerifyPEMetadata(exe, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C.PrivateMethod()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute" } ); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""M:C.PrivateMethod""> <summary>Private method</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); var output = ProcessUtilities.RunAndGetOutput(exe, startFolder: dir.Path); Assert.Equal("Hello", output.Trim()); var refDll = Path.Combine(refDir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); CleanupAllGeneratedFiles(refDir.Path); } [Fact] public void RefOutWithError() { var dir = Temp.CreateDirectory(); dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() { error(); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refout:ref/a.dll", "/deterministic", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var dll = Path.Combine(dir.Path, "a.dll"); Assert.False(File.Exists(dll)); var refDll = Path.Combine(dir.Path, Path.Combine("ref", "a.dll")); Assert.False(File.Exists(refDll)); Assert.Equal("a.cs(1,39): error CS0103: The name 'error' does not exist in the current context", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void RefOnly() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" using System; class C { /// <summary>Main method</summary> public static void Main() { error(); // semantic error in method body } private event Action E1 { add { } remove { } } private event Action E2; /// <summary>Private Class Field</summary> private int field; /// <summary>Private Struct</summary> private struct S { /// <summary>Private Struct Field</summary> private int field; } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refonly", "/debug", "/deterministic", "/langversion:7", "/doc:doc.xml", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var refDll = Path.Combine(dir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C", "TypeDefinition:S" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); var pdb = Path.Combine(dir.Path, "a.pdb"); Assert.False(File.Exists(pdb)); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""F:C.field""> <summary>Private Class Field</summary> </member> <member name=""T:C.S""> <summary>Private Struct</summary> </member> <member name=""F:C.S.field""> <summary>Private Struct Field</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/define:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '1' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("1").WithLocation(1, 1)); } [Fact] public void CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/langversion:1000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '1000' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("1000").WithLocation(1, 1)); } [Fact, WorkItem(16913, "https://github.com/dotnet/roslyn/issues/16913")] public void CompilingCodeWithMultipleInvalidPreProcessorSymbolsShouldErrorOut() { var parsedArgs = DefaultParse(new[] { "/define:valid1,2invalid,valid3", "/define:4,5,valid6", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid value for '/define'; '2invalid' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("2invalid"), // warning CS2029: Invalid value for '/define'; '4' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("4"), // warning CS2029: Invalid value for '/define'; '5' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("5")); } [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MissingCompilerAssembly() { var dir = Temp.CreateDirectory(); var cscPath = dir.CopyFile(s_CSharpCompilerExecutable).Path; dir.CopyFile(typeof(Compilation).Assembly.Location); // Missing Microsoft.CodeAnalysis.CSharp.dll. var result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(CSharpCompilation).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); // Missing System.Collections.Immutable.dll. dir.CopyFile(typeof(CSharpCompilation).Assembly.Location); result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); } #if NET472 [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void LoadinganalyzerNetStandard13() { var analyzerFileName = "AnalyzerNS13.dll"; var srcFileName = "src.cs"; var analyzerDir = Temp.CreateDirectory(); var analyzerFile = analyzerDir.CreateFile(analyzerFileName).WriteAllBytes(DesktopTestHelpers.CreateCSharpAnalyzerNetStandard13(Path.GetFileNameWithoutExtension(analyzerFileName))); var srcFile = analyzerDir.CreateFile(srcFileName).WriteAllText("public class C { }"); var result = ProcessUtilities.Run(s_CSharpCompilerExecutable, arguments: $"/nologo /t:library /analyzer:{analyzerFileName} {srcFileName}", workingDirectory: analyzerDir.Path); var outputWithoutPaths = Regex.Replace(result.Output, " in .*", ""); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"warning AD0001: Analyzer 'TestAnalyzer' threw an exception of type 'System.NotImplementedException' with message '28'. System.NotImplementedException: 28 at TestAnalyzer.get_SupportedDiagnostics() at Microsoft.CodeAnalysis.Diagnostics.AnalyzerManager.AnalyzerExecutionContext.<>c__DisplayClass20_0.<ComputeDiagnosticDescriptors>b__0(Object _) at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info) -----", outputWithoutPaths); Assert.Equal(0, result.ExitCode); } #endif [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=484417")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MicrosoftDiaSymReaderNativeAltLoadPath() { var dir = Temp.CreateDirectory(); var cscDir = Path.GetDirectoryName(s_CSharpCompilerExecutable); // copy csc and dependencies except for DSRN: foreach (var filePath in Directory.EnumerateFiles(cscDir)) { var fileName = Path.GetFileName(filePath); if (fileName.StartsWith("csc") || fileName.StartsWith("System.") || fileName.StartsWith("Microsoft.") && !fileName.StartsWith("Microsoft.DiaSymReader.Native")) { dir.CopyFile(filePath); } } dir.CreateFile("Source.cs").WriteAllText("class C { void F() { } }"); var cscCopy = Path.Combine(dir.Path, "csc.exe"); var arguments = "/nologo /t:library /debug:full Source.cs"; // env variable not set (deterministic) -- DSRN is required: var result = ProcessUtilities.Run(cscCopy, arguments + " /deterministic", workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences( "error CS0041: Unexpected error writing debug information -- 'Unable to load DLL 'Microsoft.DiaSymReader.Native.amd64.dll': " + "The specified module could not be found. (Exception from HRESULT: 0x8007007E)'", result.Output.Trim()); // env variable not set (non-deterministic) -- globally registered SymReader is picked up: result = ProcessUtilities.Run(cscCopy, arguments, workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences("", result.Output.Trim()); // env variable set: result = ProcessUtilities.Run( cscCopy, arguments + " /deterministic", workingDirectory: dir.Path, additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", cscDir) }); Assert.Equal("", result.Output.Trim()); } [ConditionalFact(typeof(WindowsOnly))] [WorkItem(21935, "https://github.com/dotnet/roslyn/issues/21935")] public void PdbPathNotEmittedWithoutPdb() { var dir = Temp.CreateDirectory(); var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var args = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug-" }; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); using (var peStream = File.OpenRead(exePath)) using (var peReader = new PEReader(peStream)) { var debugDirectory = peReader.PEHeaders.PEHeader.DebugTableDirectory; Assert.Equal(0, debugDirectory.Size); Assert.Equal(0, debugDirectory.RelativeVirtualAddress); } } [Fact] public void StrongNameProviderWithCustomTempPath() { var tempDir = Temp.CreateDirectory(); var workingDir = Temp.CreateDirectory(); workingDir.CreateFile("a.cs"); var buildPaths = new BuildPaths(clientDir: "", workingDir: workingDir.Path, sdkDir: null, tempDir: tempDir.Path); var csc = new MockCSharpCompiler(null, buildPaths, args: new[] { "/features:UseLegacyStrongNameProvider", "/nostdlib", "a.cs" }); var comp = csc.CreateCompilation(new StringWriter(), new TouchedFileLogger(), errorLogger: null); Assert.True(!comp.SignUsingBuilder); } public class QuotedArgumentTests : CommandLineTestBase { private static readonly string s_rootPath = ExecutionConditionUtil.IsWindows ? @"c:\" : "/"; private void VerifyQuotedValid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); } private void VerifyQuotedInvalid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.True(args.Errors.Length > 0); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void DebugFlag() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var list = new List<Tuple<string, DebugInformationFormat>>() { Tuple.Create("portable", DebugInformationFormat.PortablePdb), Tuple.Create("full", platformPdbKind), Tuple.Create("pdbonly", platformPdbKind), Tuple.Create("embedded", DebugInformationFormat.Embedded) }; foreach (var tuple in list) { VerifyQuotedValid("debug", tuple.Item1, tuple.Item2, x => x.EmitOptions.DebugInformationFormat); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void CodePage() { VerifyQuotedValid("codepage", "1252", 1252, x => x.Encoding.CodePage); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void Target() { var list = new List<Tuple<string, OutputKind>>() { Tuple.Create("exe", OutputKind.ConsoleApplication), Tuple.Create("winexe", OutputKind.WindowsApplication), Tuple.Create("library", OutputKind.DynamicallyLinkedLibrary), Tuple.Create("module", OutputKind.NetModule), Tuple.Create("appcontainerexe", OutputKind.WindowsRuntimeApplication), Tuple.Create("winmdobj", OutputKind.WindowsRuntimeMetadata) }; foreach (var tuple in list) { VerifyQuotedInvalid("target", tuple.Item1, tuple.Item2, x => x.CompilationOptions.OutputKind); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void PlatformFlag() { var list = new List<Tuple<string, Platform>>() { Tuple.Create("x86", Platform.X86), Tuple.Create("x64", Platform.X64), Tuple.Create("itanium", Platform.Itanium), Tuple.Create("anycpu", Platform.AnyCpu), Tuple.Create("anycpu32bitpreferred",Platform.AnyCpu32BitPreferred), Tuple.Create("arm", Platform.Arm) }; foreach (var tuple in list) { VerifyQuotedValid("platform", tuple.Item1, tuple.Item2, x => x.CompilationOptions.Platform); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void WarnFlag() { VerifyQuotedValid("warn", "1", 1, x => x.CompilationOptions.WarningLevel); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void LangVersionFlag() { VerifyQuotedValid("langversion", "2", LanguageVersion.CSharp2, x => x.ParseOptions.LanguageVersion); } } [Fact] [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] public void InvalidPathCharacterInPathMap() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pathmap:test\\=\"", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS8101: The pathmap option was incorrectly formatted.", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void InvalidPathCharacterInPdbPath() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pdb:test\\?.pdb", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2021: File name 'test\\?.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerParserWarningAsError() { string source = @" class C { long M(int i) { // warning CS0078 : The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity return 0l; } } "; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that parser warning CS0078 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0078"); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS0078", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0078", output, StringComparison.Ordinal); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_LowercaseEllSuffix, "l"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerSyntaxWarning() { // warning CS1522: Empty switch block // NOTE: Empty switch block warning is reported by the C# language parser string source = @" class C { void M(int i) { switch (i) { } } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS1522 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS1522"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_EmptySwitch), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains($"info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS1522", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerSemanticWarning() { string source = @" class C { // warning CS0169: The field 'C.f' is never used private readonly int f; }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS0169 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0169"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_UnreferencedField, "C.f"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS0169", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSyntaxError() { // error CS1001: Identifier expected string source = @" class { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler syntax error CS1001 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS1001", output, StringComparison.Ordinal); // Verify that compiler syntax error CS1001 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS1001")); Assert.Contains("error CS1001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSemanticError() { // error CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) string source = @" class C { void M(UndefinedType x) { } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler error CS0246 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0246", output, StringComparison.Ordinal); // Verify that compiler error CS0246 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS0246")); Assert.Contains("error CS0246", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_AnalyzerWarning() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer warning is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, analyzer.Descriptor.MessageFormat, suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that analyzer warning is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that "NotConfigurable" analyzer warning cannot be suppressed with diagnostic suppressor. analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: false); suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_AnalyzerError() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer error is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Error, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer error cannot be suppressed with diagnostic suppressor. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestCategoryBasedBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify category based configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify category based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify category based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify disabled by default analyzer is not enabled by category based configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify disabled by default analyzer is not enabled by category based configuration in global config analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" is_global=true dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer via global config analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; // Verify bulk configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify bulk configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify bulk configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify bulk configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify bulk configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify disabled by default analyzer is not enabled by bulk configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestMixedCategoryBasedAndBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration before bulk analyzer diagnostic configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_analyzer_diagnostic.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration after bulk analyzer diagnostic configuration is respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in analyzer config. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in ruleset. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText); } private void TestBulkAnalyzerConfigurationCore( NamedTypeAnalyzerWithConfigurableEnabledByDefault analyzer, string analyzerConfigText, bool errorlog, ReportDiagnostic expectedDiagnosticSeverity, string rulesetText = null, bool noWarn = false) { var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(analyzerConfigText); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{diagnosticId}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } if (rulesetText != null) { var rulesetFile = CreateRuleSetFile(rulesetText); arguments = arguments.Append($"/ruleset:{rulesetFile.Path}"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = expectedDiagnosticSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); var prefix = expectedDiagnosticSeverity switch { ReportDiagnostic.Error => "error", ReportDiagnostic.Warn => "warning", ReportDiagnostic.Info => errorlog ? "info" : null, ReportDiagnostic.Hidden => null, ReportDiagnostic.Suppress => null, _ => throw ExceptionUtilities.UnexpectedValue(expectedDiagnosticSeverity) }; if (prefix == null) { Assert.DoesNotContain(diagnosticId, outWriter.ToString()); } else { Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", outWriter.ToString()); } } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void CompilerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (warnAsError) { additionalArgs = additionalArgs.Append("/warnaserror").AsArray(); } var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = warnAsError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !warnAsError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !warnAsError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerConfigSeverityEscalationToErrorDoesNotEmit(bool analyzerConfigSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (analyzerConfigSetToError) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = error"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } var expectedErrorCount = analyzerConfigSetToError ? 1 : 0; var expectedWarningCount = !analyzerConfigSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = analyzerConfigSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !analyzerConfigSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !analyzerConfigSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !analyzerConfigSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void RulesetSeverityEscalationToErrorDoesNotEmit(bool rulesetSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (rulesetSetToError) { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""CS0169"" Action=""Error"" /> </Rules> </RuleSet> "; var rulesetFile = CreateRuleSetFile(source); additionalArgs = additionalArgs.Append("/ruleset:" + rulesetFile.Path).ToArray(); } var expectedErrorCount = rulesetSetToError ? 1 : 0; var expectedWarningCount = !rulesetSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = rulesetSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !rulesetSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !rulesetSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !rulesetSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C { }"); var additionalArgs = warnAsError ? new[] { "/warnaserror" } : null; var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount, analyzers: new[] { new WarningDiagnosticAnalyzer() }); var expectedDiagnosticSeverity = warnAsError ? "error" : "warning"; Assert.Contains($"{expectedDiagnosticSeverity} {WarningDiagnosticAnalyzer.Warning01.Id}", output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); } // Currently, configuring no location diagnostics through editorconfig is not supported. [Theory(Skip = "https://github.com/dotnet/roslyn/issues/38042")] [CombinatorialData] public void AnalyzerConfigRespectedForNoLocationDiagnostic(ReportDiagnostic reportDiagnostic, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new AnalyzerWithNoLocationDiagnostics(isEnabledByDefault); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, reportDiagnostic, noWarn, errorlog); } [WorkItem(37876, "https://github.com/dotnet/roslyn/issues/37876")] [Theory] [CombinatorialData] public void AnalyzerConfigRespectedForDisabledByDefaultDiagnostic(ReportDiagnostic analyzerConfigSeverity, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity: DiagnosticSeverity.Warning); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, analyzerConfigSeverity, noWarn, errorlog); } private void TestAnalyzerConfigRespectedCore(DiagnosticAnalyzer analyzer, DiagnosticDescriptor descriptor, ReportDiagnostic analyzerConfigSeverity, bool noWarn, bool errorlog) { if (analyzerConfigSeverity == ReportDiagnostic.Default) { // "dotnet_diagnostic.ID.severity = default" is not supported. return; } var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{descriptor.Id}.severity = {analyzerConfigSeverity.ToAnalyzerConfigString()}"); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{descriptor.Id}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = !noWarn && analyzerConfigSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. if (!noWarn && (analyzerConfigSeverity == ReportDiagnostic.Error || analyzerConfigSeverity == ReportDiagnostic.Warn || (analyzerConfigSeverity == ReportDiagnostic.Info && errorlog))) { var prefix = analyzerConfigSeverity == ReportDiagnostic.Error ? "error" : analyzerConfigSeverity == ReportDiagnostic.Warn ? "warning" : "info"; Assert.Contains($"{prefix} {descriptor.Id}: {descriptor.MessageFormat}", outWriter.ToString()); } else { Assert.DoesNotContain(descriptor.Id.ToString(), outWriter.ToString()); } } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public void IsUserConfiguredGeneratedCodeInAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M(C? c) { _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. } }"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable" }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = true var analyzerConfigFile = dir.CreateFile(".editorconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = true"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.DoesNotContain("warning CS8602", output, StringComparison.Ordinal); // warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source. Assert.Contains("warning CS8669", output, StringComparison.Ordinal); // generated_code = false analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = false"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = auto analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = auto"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); } [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void TestAnalyzerFilteringBasedOnSeverity(DiagnosticSeverity defaultSeverity, bool errorlog) { // This test verifies that analyzer execution is skipped at build time for the following: // 1. Analyzer reporting Hidden diagnostics // 2. Analyzer reporting Info diagnostics, when /errorlog is not specified var analyzerShouldBeSkipped = defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog; // We use an analyzer that throws an exception on every analyzer callback. // So an AD0001 analyzer exception diagnostic is reported if analyzer executed, otherwise not. var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var args = new[] { "/nologo", "/t:library", "/preferreduilang:en", src.Path }; if (errorlog) args = args.Append("/errorlog:errorlog"); var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { Assert.Contains("warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+NamedTypeAnalyzerWithConfigurableEnabledByDefault' threw an exception of type 'System.NotImplementedException'", output, StringComparison.Ordinal); } } [WorkItem(47017, "https://github.com/dotnet/roslyn/issues/47017")] [CombinatorialData, Theory] public void TestWarnAsErrorMinusDoesNotEnableDisabledByDefaultAnalyzers(DiagnosticSeverity defaultSeverity, bool isEnabledByDefault) { // This test verifies that '/warnaserror-:DiagnosticId' does not affect if analyzers are executed or skipped.. // Setup the analyzer to always throw an exception on analyzer callbacks for cases where we expect analyzer execution to be skipped: // 1. Disabled by default analyzer, i.e. 'isEnabledByDefault == false'. // 2. Default severity Hidden/Info: We only execute analyzers reporting Warning/Error severity diagnostics on command line builds. var analyzerShouldBeSkipped = !isEnabledByDefault || defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info; var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity, throwOnAllNamedTypes: analyzerShouldBeSkipped); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); // Verify '/warnaserror-:DiagnosticId' behavior. var args = new[] { "/warnaserror+", $"/warnaserror-:{diagnosticId}", "/nologo", "/t:library", "/preferreduilang:en", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedExitCode = !analyzerShouldBeSkipped && defaultSeverity == DiagnosticSeverity.Error ? 1 : 0; Assert.Equal(expectedExitCode, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { var prefix = defaultSeverity == DiagnosticSeverity.Warning ? "warning" : "error"; Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", output); } } [WorkItem(49446, "https://github.com/dotnet/roslyn/issues/49446")] [Theory] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when config file bumps severity to 'Warning' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and no config file setting is specified. [InlineData(false, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' has no effect when default severity is 'Info' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] public void TestWarnAsErrorMinusDoesNotNullifyEditorConfig( bool warnAsErrorMinus, DiagnosticSeverity defaultSeverity, DiagnosticSeverity? severityInConfigFile, DiagnosticSeverity expectedEffectiveSeverity) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: false); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var additionalFlags = new[] { "/warnaserror+" }; if (severityInConfigFile.HasValue) { var severityString = DiagnosticDescriptor.MapSeverityToReport(severityInConfigFile.Value).ToAnalyzerConfigString(); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {severityString}"); additionalFlags = additionalFlags.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray(); } if (warnAsErrorMinus) { additionalFlags = additionalFlags.Append($"/warnaserror-:{diagnosticId}").ToArray(); } int expectedWarningCount = 0, expectedErrorCount = 0; switch (expectedEffectiveSeverity) { case DiagnosticSeverity.Warning: expectedWarningCount = 1; break; case DiagnosticSeverity.Error: expectedErrorCount = 1; break; default: throw ExceptionUtilities.UnexpectedValue(expectedEffectiveSeverity); } VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, expectedWarningCount: expectedWarningCount, expectedErrorCount: expectedErrorCount, additionalFlags: additionalFlags, analyzers: new[] { analyzer }); } [Fact] public void SourceGenerators_EmbeddedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, $"generatedSource.cs"), generatedSource } }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void TestSourceGeneratorsWithAnalyzers(bool includeCurrentAssemblyAsAnalyzerReference, bool skipAnalyzers) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); // 'skipAnalyzers' should have no impact on source generator execution, but should prevent analyzer execution. var skipAnalyzersFlag = "/skipAnalyzers" + (skipAnalyzers ? "+" : "-"); // Verify analyzers were executed only if both the following conditions were satisfied: // 1. Current assembly was added as an analyzer reference, i.e. "includeCurrentAssemblyAsAnalyzerReference = true" and // 2. We did not explicitly request skipping analyzers, i.e. "skipAnalyzers = false". var expectedAnalyzerExecution = includeCurrentAssemblyAsAnalyzerReference && !skipAnalyzers; // 'WarningDiagnosticAnalyzer' generates a warning for each named type. // We expect two warnings for this test: type "C" defined in source and the source generator defined type. // Additionally, we also have an analyzer that generates "warning CS8032: An instance of analyzer cannot be created" var expectedWarningCount = expectedAnalyzerExecution ? 3 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference, expectedWarningCount: expectedWarningCount, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe", skipAnalyzersFlag }, generators: new[] { generator }); // Verify source generator was executed, regardless of the value of 'skipAnalyzers'. var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, "generatedSource.cs"), generatedSource } }, dir, true); if (expectedAnalyzerExecution) { Assert.Contains("warning Warning01", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); } else { Assert.Empty(output); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_EmbeddedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generator1Prefix, source1Name), source1}, { Path.Combine(dir.Path, generator2Prefix, source2Name), source2}, }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_WriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_OverwriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource1 = "class D { } class E { }"; var generator1 = new SingleFileTestGenerator(generatedSource1, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator1 }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator1); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource1 } } } }); var generatedSource2 = "public class D { }"; var generator2 = new SingleFileTestGenerator(generatedSource2, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator2 }, analyzers: null); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_WriteGeneratedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generator1Prefix), new() { { source1Name, source1 } } }, { Path.Combine(generatedDir.Path, generator2Prefix), new() { { source2Name, source2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [ConditionalFact(typeof(DesktopClrOnly))] //CoreCLR doesn't support SxS loading [WorkItem(47990, "https://github.com/dotnet/roslyn/issues/47990")] public void SourceGenerators_SxS_AssemblyLoading() { // compile the generators var dir = Temp.CreateDirectory(); var snk = Temp.CreateFile("TestKeyPair_", ".snk", dir.Path).WriteAllBytes(TestResources.General.snKey); var src = dir.CreateFile("generator.cs"); var virtualSnProvider = new DesktopStrongNameProvider(ImmutableArray.Create(dir.Path)); string createGenerator(string version) { var generatorSource = $@" using Microsoft.CodeAnalysis; [assembly:System.Reflection.AssemblyVersion(""{version}"")] [Generator] public class TestGenerator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ context.AddSource(""generatedSource.cs"", ""//from version {version}""); }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var path = Path.Combine(dir.Path, Guid.NewGuid().ToString() + ".dll"); var comp = CreateEmptyCompilation(source: generatorSource, references: TargetFrameworkUtil.NetStandard20References.Add(MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly)), options: TestOptions.DebugDll.WithCryptoKeyFile(Path.GetFileName(snk.Path)).WithStrongNameProvider(virtualSnProvider), assemblyName: "generator"); comp.VerifyDiagnostics(); comp.Emit(path); return path; } var gen1 = createGenerator("1.0.0.0"); var gen2 = createGenerator("2.0.0.0"); var generatedDir = dir.CreateDirectory("generated"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/analyzer:" + gen1, "/analyzer:" + gen2 }.ToArray()); // This is wrong! Both generators are writing the same file out, over the top of each other // See https://github.com/dotnet/roslyn/issues/47990 ValidateWrittenSources(new() { // { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 1.0.0.0" } } }, { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 2.0.0.0" } } } }); } [Fact] public void SourceGenerators_DoNotWriteGeneratedSources_When_No_Directory_Supplied() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); ValidateWrittenSources(new() { { generatedDir.Path, new() } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_Error_When_GeneratedDir_NotExist() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDirPath = Path.Combine(dir.Path, "noexist"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); var output = VerifyOutput(dir, src, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDirPath, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); Assert.Contains("CS0016:", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_GeneratedDir_Has_Spaces() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated files"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void ParseGeneratedFilesOut() { string root = PathUtilities.IsUnixLikePlatform ? "/" : "c:\\"; string baseDirectory = Path.Combine(root, "abc", "def"); var parsedArgs = DefaultParse(new[] { @"/generatedfilesout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:\"\"")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:outdir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""outdir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:out dir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""out dir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); var absPath = Path.Combine(root, "outdir"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); absPath = Path.Combine(root, "generated files"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); } [Fact] public void SourceGenerators_Error_When_NoDirectoryArgumentGiven() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var output = VerifyOutput(dir, src, expectedErrorCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:", "/langversion:preview", "/out:embed.exe" }); Assert.Contains("error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_ReportedWrittenFiles_To_TouchedFilesLogger() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, $"/touchedfiles:{dir.Path}/touched", "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var touchedFiles = Directory.GetFiles(dir.Path, "touched*"); Assert.Equal(2, touchedFiles.Length); string[] writtenText = File.ReadAllLines(Path.Combine(dir.Path, "touched.write")); Assert.Equal(2, writtenText.Length); Assert.EndsWith("EMBED.EXE", writtenText[0], StringComparison.OrdinalIgnoreCase); Assert.EndsWith("GENERATEDSOURCE.CS", writtenText[1], StringComparison.OrdinalIgnoreCase); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44087")] public void SourceGeneratorsAndAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key = value"); var generator = new SingleFileTestGenerator("public class D {}", "generated.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path }, generators: new[] { generator }, analyzers: null); } [Fact] public void SourceGeneratorsCanReadAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig1 = dir.CreateFile(".globaleditorconfig").WriteAllText(@" is_global = true key1 = value1 [*.cs] key2 = value2 [*.vb] key3 = value3"); var analyzerConfig2 = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key4 = value4 [*.vb] key5 = value5"); var subDir = dir.CreateDirectory("subDir"); var analyzerConfig3 = subDir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key6 = value6 [*.vb] key7 = value7"); var generator = new CallbackGenerator((ic) => { }, (gc) => { // can get the global options var globalOptions = gc.AnalyzerConfigOptions.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // can get the options for class C var classOptions = gc.AnalyzerConfigOptions.GetOptions(gc.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); }); var args = new[] { "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, "/analyzerconfig:" + analyzerConfig3.Path, "/t:library", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, generators: ImmutableArray.Create<ISourceGenerator>(generator)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); // test for both the original tree and the generated one var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; // get the global options var globalOptions = provider.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // get the options for class C var classOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); // get the options for generated class D var generatedOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.Last()); Assert.True(generatedOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(generatedOptions.TryGetValue("key2", out _)); Assert.False(generatedOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(generatedOptions.TryGetValue("key5", out _)); Assert.False(generatedOptions.TryGetValue("key6", out _)); Assert.False(generatedOptions.TryGetValue("key7", out _)); } [Theory] [CombinatorialData] public void SourceGeneratorsRunRegardlessOfLanguageVersion(LanguageVersion version) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@"class C {}"); var generator = new CallbackGenerator(i => { }, e => throw null); var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:" + version.ToDisplayString() }, generators: new[] { generator }, expectedWarningCount: 1, expectedErrorCount: 1, expectedExitCode: 0); Assert.Contains("CS8785: Generator 'CallbackGenerator' failed to generate source.", output); } [DiagnosticAnalyzer(LanguageNames.CSharp)] private sealed class FieldAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor _rule = new DiagnosticDescriptor("Id", "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration); } private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) { } } [Fact] [WorkItem(44000, "https://github.com/dotnet/roslyn/issues/44000")] public void TupleField_ForceComplete() { var source = @"namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { Item1 = item1; } } }"; var srcFile = Temp.CreateFile().WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler( null, WorkingDirectory, new[] { "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new FieldAnalyzer())); // at least one analyzer required var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Empty(output); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void GlobalAnalyzerConfigsAllowedInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" is_global = true "; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); } [Fact] public void GlobalAnalyzerConfigMultipleSetKeys() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfigFile = dir.CreateFile(".globalconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 option1 = abc"); var analyzerConfigFile2 = dir.CreateFile(".globalconfig2"); var analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 option1 = def"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'Global Section'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'Global Section'", output, StringComparison.Ordinal); analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = abc"); analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = def"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'file.cs'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'/file.cs'", output, StringComparison.Ordinal); } [Fact] public void GlobalAnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key1 = value1 [*.txt] key2 = value2"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true key3 = value3"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzerconfig:" + globalConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032,Warning01", "/additionalfile:" + additionalFile.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = provider.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("key1", out string val)); Assert.Equal("value1", val); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.True(options.TryGetValue("key2", out val)); Assert.Equal("value2", val); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GlobalOptions; Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigDiagnosticOptionsCanBeOverridenByCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.CS0164.severity = error; "); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.CS0164.severity = warning; "); var none = Array.Empty<TempFile>(); var globalOnly = new[] { globalConfig }; var globalAndSpecific = new[] { globalConfig, analyzerConfig }; // by default a warning, which can be suppressed via cmdline verify(configs: none, expectedWarnings: 1); verify(configs: none, noWarn: "CS0164", expectedWarnings: 0); // the global analyzer config ups the warning to an error, but the cmdline setting overrides it verify(configs: globalOnly, expectedErrors: 1); verify(configs: globalOnly, noWarn: "CS0164", expectedWarnings: 0); verify(configs: globalOnly, noWarn: "164", expectedWarnings: 0); // cmdline can be shortened, but still works // the editor config downgrades the error back to warning, but the cmdline setting overrides it verify(configs: globalAndSpecific, expectedWarnings: 1); verify(configs: globalAndSpecific, noWarn: "CS0164", expectedWarnings: 0); void verify(TempFile[] configs, int expectedWarnings = 0, int expectedErrors = 0, string noWarn = "0") => VerifyOutput(dir, src, expectedErrorCount: expectedErrors, expectedWarningCount: expectedWarnings, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: null, additionalFlags: configs.SelectAsArray(c => "/analyzerconfig:" + c.Path) .Add("/noWarn:" + noWarn).ToArray()); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSpecificDiagnosticOptionsOverrideGeneralCommandLineOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = none; "); VerifyOutput(dir, src, additionalFlags: new[] { "/warnaserror+", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false); } [Theory, CombinatorialData] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void WarnAsErrorIsRespectedForForWarningsConfiguredInRulesetOrGlobalConfig(bool useGlobalConfig) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var additionalFlags = new[] { "/warnaserror+" }; if (useGlobalConfig) { var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = warning; "); additionalFlags = additionalFlags.Append("/analyzerconfig:" + globalConfig.Path).ToArray(); } else { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""15.0""> <Rules AnalyzerId=""Compiler"" RuleNamespace=""Compiler""> <Rule Id=""CS0164"" Action=""Warning"" /> </Rules> </RuleSet> "; _ = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); additionalFlags = additionalFlags.Append("/ruleset:Rules.ruleset").ToArray(); } VerifyOutput(dir, src, additionalFlags: additionalFlags, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSectionsDoNotOverrideCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true [{PathUtilities.NormalizeWithForwardSlash(src.Path)}] dotnet_diagnostic.CS0164.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:0164", "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 0, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigCanSetDiagnosticWithNoLocation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.Warning01.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:Warning01", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); } [Theory, CombinatorialData] public void TestAdditionalFileAnalyzer(bool registerFromInitialize) { var srcDirectory = Temp.CreateDirectory(); var source = "class C { }"; var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); var additionalText = "Additional Text"; var additionalFile = srcDirectory.CreateFile("b.txt"); additionalFile.WriteAllText(additionalText); var diagnosticSpan = new TextSpan(2, 2); var analyzer = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/additionalfile:" + additionalFile.Path }, analyzers: analyzer); Assert.Contains("b.txt(1,3): warning ID0001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcDirectory.Path); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:CS0169" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_CompilerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var src = @" class C { int _f; // CS0169: unused field }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, diagnosticId: "CS0169", analyzerConfigSeverity, additionalArg, expectError, expectWarning); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:DiagnosticId" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_AnalyzerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var src = @"class C { }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, CompilationAnalyzerWithSeverity.DiagnosticId, analyzerConfigSeverity, additionalArg, expectError, expectWarning, analyzer); } private void TestCompilationOptionsOverrideAnalyzerConfigCore( string source, string diagnosticId, string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning, params DiagnosticAnalyzer[] analyzers) { Assert.True(!expectError || !expectWarning); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(source); var additionalArgs = Array.Empty<string>(); if (analyzerConfigSeverity != null) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {analyzerConfigSeverity}"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } if (!string.IsNullOrEmpty(additionalArg)) { additionalArgs = additionalArgs.Append(additionalArg); } var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectError ? 1 : 0, expectedWarningCount: expectWarning ? 1 : 0, analyzers: analyzers); if (expectError) { Assert.Contains($"error {diagnosticId}", output); } else if (expectWarning) { Assert.Contains($"warning {diagnosticId}", output); } else { Assert.DoesNotContain(diagnosticId, output); } } [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a coreclr targeting generator on net framework / mono")] public void TestGeneratorsCantTargetNetFramework() { var directory = Temp.CreateDirectory(); var src = directory.CreateFile("test.cs").WriteAllText(@" class C { }"); // core var coreGenerator = emitGenerator(".NETCoreApp,Version=v5.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + coreGenerator }); // netstandard var nsGenerator = emitGenerator(".NETStandard,Version=v2.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + nsGenerator }); // no target var ntGenerator = emitGenerator(targetFramework: null); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + ntGenerator }); // framework var frameworkGenerator = emitGenerator(".NETFramework,Version=v4.7.2"); var output = VerifyOutput(directory, src, expectedWarningCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8850", output); // ref's net fx Assert.Contains("CS8033", output); // no analyzers in assembly // framework, suppressed output = VerifyOutput(directory, src, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850", "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8033", output); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850,CS8033", "/analyzer:" + frameworkGenerator }); string emitGenerator(string targetFramework) { string targetFrameworkAttributeText = targetFramework is object ? $"[assembly: System.Runtime.Versioning.TargetFramework(\"{targetFramework}\")]" : string.Empty; string generatorSource = $@" using Microsoft.CodeAnalysis; {targetFrameworkAttributeText} [Generator] public class Generator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var directory = Temp.CreateDirectory(); var generatorPath = Path.Combine(directory.Path, "generator.dll"); var compilation = CSharpCompilation.Create($"generator", new[] { CSharpSyntaxTree.ParseText(generatorSource) }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, new[] { MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly) }), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); compilation.VerifyDiagnostics(); var result = compilation.Emit(generatorPath); Assert.True(result.Success); return generatorPath; } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal abstract class CompilationStartedAnalyzer : DiagnosticAnalyzer { public abstract override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public abstract void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class HiddenDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Hidden01 = new DiagnosticDescriptor("Hidden01", "", "Throwing a diagnostic for #region", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Hidden02 = new DiagnosticDescriptor("Hidden02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Hidden01, Hidden02); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(Hidden01, context.Node.GetLocation())); } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.RegionDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class InfoDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Info01 = new DiagnosticDescriptor("Info01", "", "Throwing a diagnostic for #pragma restore", "", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Info01); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { if ((context.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.RestoreKeyword)) { context.ReportDiagnostic(Diagnostic.Create(Info01, context.Node.GetLocation())); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.PragmaWarningDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class WarningDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Warning01 = new DiagnosticDescriptor("Warning01", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Warning01); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSymbolAction( (symbolContext) => { symbolContext.ReportDiagnostic(Diagnostic.Create(Warning01, symbolContext.Symbol.Locations.First())); }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class ErrorDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Error01 = new DiagnosticDescriptor("Error01", "", "Throwing a diagnostic for #pragma disable", "", DiagnosticSeverity.Error, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Error02 = new DiagnosticDescriptor("Error02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Error01, Error02); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction( (nodeContext) => { if ((nodeContext.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword)) { nodeContext.ReportDiagnostic(Diagnostic.Create(Error01, nodeContext.Node.GetLocation())); } }, SyntaxKind.PragmaWarningDirectiveTrivia ); } } }
1
dotnet/roslyn
55,098
Use directory-scoped ALCs to load analyzers in .NET Core
Resolves #52177
RikkiGibson
2021-07-23T23:26:39Z
2021-08-23T19:01:28Z
e079a36f3ade7cda2a464e4fdcde0a11577fd1ea
99f45b7c174d1a2e9b6a1d810b4069600c80421d
Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177
./src/Compilers/Core/CodeAnalysisTest/Analyzers/AnalyzerFileReferenceTests.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.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class AnalyzerFileReferenceTests : TestBase { private static readonly AnalyzerAssemblyLoader s_analyzerLoader = new DefaultAnalyzerAssemblyLoader(); public static AnalyzerFileReference CreateAnalyzerFileReference(string fullPath) { return new AnalyzerFileReference(fullPath, s_analyzerLoader); } [Fact] public void AnalyzerFileReference_Errors() { Assert.Throws<ArgumentNullException>("fullPath", () => new AnalyzerFileReference(null!, s_analyzerLoader)); Assert.Throws<ArgumentNullException>("assemblyLoader", () => new AnalyzerFileReference(TempRoot.Root, null!)); // path must be absolute Assert.Throws<ArgumentException>("fullPath", () => new AnalyzerFileReference("a.dll", s_analyzerLoader)); } [Fact] public void DisplayAndId_BadPath() { var loader = new TestAnalyzerAssemblyLoader(loadFromPath: _ => throw new Exception()); var refBadPath = new AnalyzerFileReference(PathUtilities.CombinePathsUnchecked(TempRoot.Root, "\0<>|*.xyz"), loader); Assert.Equal("\0<>|*", refBadPath.Display); Assert.Equal("\0<>|*", refBadPath.Id); } [Fact] public void Equality() { var path1 = Path.Combine(TempRoot.Root, "dir"); var path2 = Path.Combine(TempRoot.Root, "dir", "..", "dir"); // Equals/GetHashCode should not load the analyzer var loader1 = new TestAnalyzerAssemblyLoader(loadFromPath: _ => throw new InvalidOperationException()); var loader2 = new TestAnalyzerAssemblyLoader(loadFromPath: _ => throw new InvalidOperationException()); var refA = new AnalyzerFileReference(path1, loader1); var refB = new AnalyzerFileReference(path1, loader1); Assert.False(refA.Equals(null)); Assert.True(refA.Equals(refA)); Assert.True(refA.Equals(refB)); Assert.Equal(refA.GetHashCode(), refB.GetHashCode()); // paths are compared for exact equality, it's up to the host to normalize them: Assert.False(refA.Equals(new AnalyzerFileReference(path2, loader1))); // different loader: Assert.False(refA.Equals(new AnalyzerFileReference(path1, loader2))); // legacy overload: Assert.True(refA.Equals((AnalyzerReference)refA)); Assert.False(refA.Equals((AnalyzerReference?)null)); Assert.True(refA!.Equals((AnalyzerReference)refB)); Assert.True(refA.Equals(new TestAnalyzerReference(path1))); Assert.False(refA.Equals(new TestAnalyzerReference(path2))); } [Fact] public void TestMetadataParse() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var analyzerTypeNameMap = reference.GetAnalyzerTypeNameMap(); Assert.Equal(2, analyzerTypeNameMap.Keys.Count()); Assert.Equal(6, analyzerTypeNameMap[LanguageNames.CSharp].Count); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzerCS", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.TestAnalyzerCSVB", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzer", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedAnalyzer", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AbstractAnalyzer", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.OpenGenericAnalyzer`1", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.DoesNotContain("Microsoft.CodeAnalysis.UnitTests.Test.NotAnAnalyzer", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.Equal(6, analyzerTypeNameMap[LanguageNames.VisualBasic].Count); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzerVB", analyzerTypeNameMap[LanguageNames.VisualBasic]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.TestAnalyzerCSVB", analyzerTypeNameMap[LanguageNames.VisualBasic]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzer", analyzerTypeNameMap[LanguageNames.VisualBasic]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedAnalyzer", analyzerTypeNameMap[LanguageNames.VisualBasic]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AbstractAnalyzer", analyzerTypeNameMap[LanguageNames.VisualBasic]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.OpenGenericAnalyzer`1", analyzerTypeNameMap[LanguageNames.VisualBasic]); Assert.DoesNotContain("Microsoft.CodeAnalysis.UnitTests.Test.NotAnAnalyzer", analyzerTypeNameMap[LanguageNames.VisualBasic]); } [Fact] public void TestGetAnalyzersPerLanguage() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var analyzers = reference.GetAnalyzers(LanguageNames.CSharp); Assert.Equal(4, analyzers.Length); var analyzerNames = analyzers.Select(a => a.GetType().Name); Assert.Contains("TestAnalyzer", analyzerNames); Assert.Contains("TestAnalyzerCS", analyzerNames); Assert.Contains("TestAnalyzerCSVB", analyzerNames); Assert.Contains("NestedAnalyzer", analyzerNames); analyzers = reference.GetAnalyzers(LanguageNames.VisualBasic); analyzerNames = analyzers.Select(a => a.GetType().Name); Assert.Equal(4, analyzers.Length); Assert.Contains("TestAnalyzerVB", analyzerNames); Assert.Contains("TestAnalyzerCSVB", analyzerNames); Assert.Contains("TestAnalyzer", analyzerNames); Assert.Contains("NestedAnalyzer", analyzerNames); } [Fact] public void TestLoadErrors1() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); List<AnalyzerLoadFailureEventArgs> errors = new List<AnalyzerLoadFailureEventArgs>(); EventHandler<AnalyzerLoadFailureEventArgs> errorHandler = (o, e) => errors.Add(e); reference.AnalyzerLoadFailed += errorHandler; var builder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); reference.AddAnalyzers(builder, LanguageNames.CSharp); var analyzers = builder.ToImmutable(); reference.AnalyzerLoadFailed -= errorHandler; Assert.Equal(2, errors.Count); var failedTypes = errors.Where(e => e.ErrorCode == AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer).Select(e => e.TypeName); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AbstractAnalyzer", failedTypes); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.OpenGenericAnalyzer`1", failedTypes); } [Fact] public void TestLoadErrors2() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Path.Combine(TempRoot.Root, "random.dll")); List<AnalyzerLoadFailureEventArgs> errors = new List<AnalyzerLoadFailureEventArgs>(); EventHandler<AnalyzerLoadFailureEventArgs> errorHandler = (o, e) => errors.Add(e); reference.AnalyzerLoadFailed += errorHandler; var builder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); reference.AddAnalyzers(builder, LanguageNames.CSharp); var analyzers = builder.ToImmutable(); reference.AnalyzerLoadFailed -= errorHandler; Assert.Equal(1, errors.Count); Assert.Equal(AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer, errors.First().ErrorCode); } [Fact] public void TestLoadErrors3() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); AnalyzerFileReference reference = CreateAnalyzerFileReference(alphaDll.Path); List<AnalyzerLoadFailureEventArgs> errors = new List<AnalyzerLoadFailureEventArgs>(); EventHandler<AnalyzerLoadFailureEventArgs> errorHandler = (o, e) => errors.Add(e); reference.AnalyzerLoadFailed += errorHandler; var builder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); reference.AddAnalyzers(builder, LanguageNames.CSharp); var analyzers = builder.ToImmutable(); reference.AnalyzerLoadFailed -= errorHandler; File.Delete(alphaDll.Path); Assert.Equal(0, errors.Count); } [Fact] [WorkItem(1029928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029928")] public void BadAnalyzerReference_DisplayName() { var directory = Temp.CreateDirectory(); var textFile = directory.CreateFile("Goo.txt").WriteAllText("I am the very model of a modern major general."); AnalyzerFileReference reference = CreateAnalyzerFileReference(textFile.Path); Assert.Equal(expected: "Goo", actual: reference.Display); } [Fact] public void ValidAnalyzerReference_DisplayName() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); AnalyzerFileReference reference = CreateAnalyzerFileReference(alphaDll.Path); Assert.Equal(expected: "Alpha", actual: reference.Display); } [Fact] [WorkItem(2781, "https://github.com/dotnet/roslyn/issues/2781")] [WorkItem(2782, "https://github.com/dotnet/roslyn/issues/2782")] public void ValidAnalyzerReference_Id() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); AnalyzerFileReference reference = CreateAnalyzerFileReference(alphaDll.Path); AssemblyIdentity.TryParseDisplayName("Alpha, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", out var expectedIdentity); Assert.Equal(expected: expectedIdentity, actual: reference.Id); } [Fact] [WorkItem(2781, "https://github.com/dotnet/roslyn/issues/2781")] [WorkItem(2782, "https://github.com/dotnet/roslyn/issues/2782")] public void BadAnalyzerReference_Id() { var directory = Temp.CreateDirectory(); var textFile = directory.CreateFile("Goo.txt").WriteAllText("I am the very model of a modern major general."); AnalyzerFileReference reference = CreateAnalyzerFileReference(textFile.Path); Assert.Equal(expected: "Goo", actual: reference.Id); } [Fact] [WorkItem(1032909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032909")] public void TestFailedLoadDoesntCauseNoAnalyzersWarning() { var directory = Temp.CreateDirectory(); var analyzerDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AnalyzerTests.FaultyAnalyzer); AnalyzerFileReference reference = CreateAnalyzerFileReference(analyzerDll.Path); List<AnalyzerLoadFailureEventArgs> errors = new List<AnalyzerLoadFailureEventArgs>(); EventHandler<AnalyzerLoadFailureEventArgs> errorHandler = (o, e) => errors.Add(e); reference.AnalyzerLoadFailed += errorHandler; var builder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); reference.AddAnalyzers(builder, LanguageNames.CSharp); var analyzers = builder.ToImmutable(); reference.AnalyzerLoadFailed -= errorHandler; Assert.Equal(1, errors.Count); Assert.Equal(AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer, errors.First().ErrorCode); } [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a framework targeting generator, which these are in desktop")] public void TestLoadGenerators() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var generators = reference.GetGeneratorsForAllLanguages(); var typeNames = generators.Select(g => g.GetGeneratorType().FullName); AssertEx.SetEqual(new[] { "Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", "Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", "Microsoft.CodeAnalysis.UnitTests.TestGenerator", "Microsoft.CodeAnalysis.UnitTests.BaseGenerator", "Microsoft.CodeAnalysis.UnitTests.SubClassedGenerator", "Microsoft.CodeAnalysis.UnitTests.ExplicitCSharpOnlyGenerator", "Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator", "Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", "Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", "Microsoft.CodeAnalysis.UnitTests.FSharpGenerator", "Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", "Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator" }, typeNames); } [ConditionalFact(typeof(CoreClrOnly))] public void TestLoadGeneratorsWithoutArgumentOnlyLoadsCSharp() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var generators = reference.GetGenerators(LanguageNames.CSharp); #pragma warning disable CS0618 // Type or member is obsolete var generators2 = reference.GetGenerators(); #pragma warning restore CS0618 // Type or member is obsolete Assert.Equal(generators, generators2); } [ConditionalFact(typeof(CoreClrOnly))] public void TestLoadCSharpGenerators() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var generators = reference.GetGenerators(LanguageNames.CSharp); var typeNames = generators.Select(g => g.GetGeneratorType().FullName); AssertEx.SetEqual(new[] { "Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", "Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", "Microsoft.CodeAnalysis.UnitTests.TestGenerator", "Microsoft.CodeAnalysis.UnitTests.BaseGenerator", "Microsoft.CodeAnalysis.UnitTests.SubClassedGenerator", "Microsoft.CodeAnalysis.UnitTests.ExplicitCSharpOnlyGenerator", "Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", "Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", "Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", "Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator" }, typeNames); } [ConditionalFact(typeof(CoreClrOnly))] public void TestLoadVisualBasicGenerators() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var generators = reference.GetGenerators(LanguageNames.VisualBasic); var typeNames = generators.Select(g => g.GetGeneratorType().FullName); AssertEx.SetEqual(new[] { "Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator", "Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", "Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", "Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", "Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator" }, typeNames); } // can't load a coreclr targeting generator on net framework / mono [ConditionalFact(typeof(CoreClrOnly))] public void TestGeneratorsCantTargetNetFramework() { var directory = Temp.CreateDirectory(); // core var errors = buildAndLoadGeneratorAndReturnAnyErrors(".NETCoreApp,Version=v5.0"); Assert.Empty(errors); // netstandard errors = buildAndLoadGeneratorAndReturnAnyErrors(".NETStandard,Version=v2.0"); Assert.Empty(errors); // no target errors = buildAndLoadGeneratorAndReturnAnyErrors(targetFramework: null); Assert.Empty(errors); // framework errors = buildAndLoadGeneratorAndReturnAnyErrors(".NETFramework,Version=v4.7.2"); Assert.Equal(2, errors.Count); Assert.Equal(AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework, errors.First().ErrorCode); List<AnalyzerLoadFailureEventArgs> buildAndLoadGeneratorAndReturnAnyErrors(string? targetFramework) { string targetFrameworkAttributeText = targetFramework is object ? $"[assembly: System.Runtime.Versioning.TargetFramework(\"{targetFramework}\")]" : string.Empty; string generatorSource = $@" using Microsoft.CodeAnalysis; {targetFrameworkAttributeText} [Generator] public class Generator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var directory = Temp.CreateDirectory(); var generatorPath = Path.Combine(directory.Path, "generator.dll"); var compilation = CSharpCompilation.Create($"generator_{targetFramework}", new[] { CSharpSyntaxTree.ParseText(generatorSource) }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, new[] { MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly) }), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); compilation.VerifyDiagnostics(); var result = compilation.Emit(generatorPath); Assert.True(result.Success); AnalyzerFileReference reference = CreateAnalyzerFileReference(generatorPath); List<AnalyzerLoadFailureEventArgs> errors = new List<AnalyzerLoadFailureEventArgs>(); void errorHandler(object? o, AnalyzerLoadFailureEventArgs e) => errors.Add(e); reference.AnalyzerLoadFailed += errorHandler; var builder = ImmutableArray.CreateBuilder<ISourceGenerator>(); reference.AddGenerators(builder, LanguageNames.CSharp); reference.AnalyzerLoadFailed -= errorHandler; if (errors.Count > 0) { Assert.Empty(builder); } else { Assert.Single(builder); } return errors; } } [Fact] [WorkItem(52035, "https://github.com/dotnet/roslyn/issues/52035")] public void TestLoadedAnalyzerOrderIsDeterministic() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var csharpAnalyzers = reference.GetAnalyzers(LanguageNames.CSharp).Select(a => a.GetType().FullName).ToArray(); Assert.Equal(4, csharpAnalyzers.Length); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedAnalyzer", csharpAnalyzers[0]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzer", csharpAnalyzers[1]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzerCS", csharpAnalyzers[2]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestAnalyzerCSVB", csharpAnalyzers[3]); var vbAnalyzers = reference.GetAnalyzers(LanguageNames.VisualBasic).Select(a => a.GetType().FullName).ToArray(); Assert.Equal(4, vbAnalyzers.Length); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedAnalyzer", vbAnalyzers[0]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzer", vbAnalyzers[1]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzerVB", vbAnalyzers[2]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestAnalyzerCSVB", vbAnalyzers[3]); // analyzers return C#, then VB, including duplicates var allAnalyzers = reference.GetAnalyzersForAllLanguages().Select(a => a.GetType().FullName).ToArray(); Assert.Equal(8, allAnalyzers.Length); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedAnalyzer", allAnalyzers[0]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzer", allAnalyzers[1]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzerCS", allAnalyzers[2]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestAnalyzerCSVB", allAnalyzers[3]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedAnalyzer", allAnalyzers[4]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzer", allAnalyzers[5]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzerVB", allAnalyzers[6]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestAnalyzerCSVB", allAnalyzers[7]); } [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a framework targeting generator, which these are in desktop")] [WorkItem(52035, "https://github.com/dotnet/roslyn/issues/52035")] public void TestLoadedGeneratorOrderIsDeterministic() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var csharpGenerators = reference.GetGenerators(LanguageNames.CSharp).Select(g => g.GetGeneratorType().FullName).ToArray(); Assert.Equal(10, csharpGenerators.Length); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", csharpGenerators[0]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", csharpGenerators[1]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.BaseGenerator", csharpGenerators[2]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", csharpGenerators[3]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.ExplicitCSharpOnlyGenerator", csharpGenerators[4]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.SubClassedGenerator", csharpGenerators[5]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestGenerator", csharpGenerators[6]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator", csharpGenerators[7]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", csharpGenerators[8]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", csharpGenerators[9]); var vbGenerators = reference.GetGenerators(LanguageNames.VisualBasic).Select(g => g.GetGeneratorType().FullName).ToArray(); Assert.Equal(5, vbGenerators.Length); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", vbGenerators[0]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator", vbGenerators[1]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", vbGenerators[2]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", vbGenerators[3]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator", vbGenerators[4]); // generators load in language order (C#, F#, VB), and *do not* include duplicates var allGenerators = reference.GetGeneratorsForAllLanguages().Select(g => g.GetGeneratorType().FullName).ToArray(); Assert.Equal(12, allGenerators.Length); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", allGenerators[0]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", allGenerators[1]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.BaseGenerator", allGenerators[2]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", allGenerators[3]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.ExplicitCSharpOnlyGenerator", allGenerators[4]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.SubClassedGenerator", allGenerators[5]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestGenerator", allGenerators[6]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator", allGenerators[7]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", allGenerators[8]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", allGenerators[9]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.FSharpGenerator", allGenerators[10]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator", allGenerators[11]); } // NOTE: the order in which these are emitted can change the test 'TestLoadedAnalyzerOrderIsDeterministic' // and other determinism tests in this file. // Ensure you do not re-arrange them alphabetically, as that will invalidate the tests, without // explicitly failing them [DiagnosticAnalyzer(LanguageNames.CSharp, new string[] { LanguageNames.VisualBasic })] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class TestAnalyzerCS : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } [DiagnosticAnalyzer(LanguageNames.VisualBasic, new string[] { })] public class TestAnalyzerVB : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } [Generator] public class TestGenerator : ISourceGenerator { public void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); public void Initialize(GeneratorInitializationContext context) => throw new NotImplementedException(); } public class SomeType { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class NestedAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } [Generator] public class NestedGenerator : ISourceGenerator { public void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); public void Initialize(GeneratorInitializationContext context) => throw new NotImplementedException(); } } } namespace Test { public class DiagnosticAnalyzer : Attribute { } [Test.DiagnosticAnalyzer] public class NotAnAnalyzer { } public class Generator : Attribute { } [Test.Generator] public class NotAGenerator { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class TestAnalyzerCSVB : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } public class TestAnalyzerNone { } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public abstract class AbstractAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class OpenGenericAnalyzer<T> : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } [Generator] public class TestGenerator : ISourceGenerator { public void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); public void Initialize(GeneratorInitializationContext context) => throw new NotImplementedException(); } public class TestGeneratorNoAttrib : ISourceGenerator { public void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); public void Initialize(GeneratorInitializationContext context) => throw new NotImplementedException(); } [Generator] public class BaseGenerator : ISourceGenerator { public virtual void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); public void Initialize(GeneratorInitializationContext context) => throw new NotImplementedException(); } [Generator] public class SubClassedGenerator : BaseGenerator { public override void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); } [Generator] public class NotAGenerator { } [Generator(LanguageNames.CSharp)] public class ExplicitCSharpOnlyGenerator : TestGenerator { } [Generator(LanguageNames.VisualBasic)] public class VisualBasicOnlyGenerator : TestGenerator { } [Generator(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class CSharpAndVisualBasicGenerator : TestGenerator { } [Generator(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class VisualBasicAndCSharpGenerator : TestGenerator { } [Generator(LanguageNames.FSharp)] public class FSharpGenerator : TestGenerator { } [Generator(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class TestIncrementalGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) => throw new NotImplementedException(); } public class TestIncrementalGeneratorWithNoAttrib : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) => throw new NotImplementedException(); } [Generator(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class TestSourceAndIncrementalGenerator : IIncrementalGenerator, ISourceGenerator { public void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); public void Initialize(IncrementalGeneratorInitializationContext context) => throw new NotImplementedException(); public void Initialize(GeneratorInitializationContext context) => throw new NotImplementedException(); } }
// 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.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { [Collection(AssemblyLoadTestFixtureCollection.Name)] public class AnalyzerFileReferenceTests : TestBase { private static readonly AnalyzerAssemblyLoader s_analyzerLoader = new DefaultAnalyzerAssemblyLoader(); private readonly AssemblyLoadTestFixture _testFixture; public AnalyzerFileReferenceTests(AssemblyLoadTestFixture testFixture) { _testFixture = testFixture; } public static AnalyzerFileReference CreateAnalyzerFileReference(string fullPath) { return new AnalyzerFileReference(fullPath, s_analyzerLoader); } [Fact] public void AnalyzerFileReference_Errors() { Assert.Throws<ArgumentNullException>("fullPath", () => new AnalyzerFileReference(null!, s_analyzerLoader)); Assert.Throws<ArgumentNullException>("assemblyLoader", () => new AnalyzerFileReference(TempRoot.Root, null!)); // path must be absolute Assert.Throws<ArgumentException>("fullPath", () => new AnalyzerFileReference("a.dll", s_analyzerLoader)); } [Fact] public void DisplayAndId_BadPath() { var loader = new TestAnalyzerAssemblyLoader(loadFromPath: _ => throw new Exception()); var refBadPath = new AnalyzerFileReference(PathUtilities.CombinePathsUnchecked(TempRoot.Root, "\0<>|*.xyz"), loader); Assert.Equal("\0<>|*", refBadPath.Display); Assert.Equal("\0<>|*", refBadPath.Id); } [Fact] public void Equality() { var path1 = Path.Combine(TempRoot.Root, "dir"); var path2 = Path.Combine(TempRoot.Root, "dir", "..", "dir"); // Equals/GetHashCode should not load the analyzer var loader1 = new TestAnalyzerAssemblyLoader(loadFromPath: _ => throw new InvalidOperationException()); var loader2 = new TestAnalyzerAssemblyLoader(loadFromPath: _ => throw new InvalidOperationException()); var refA = new AnalyzerFileReference(path1, loader1); var refB = new AnalyzerFileReference(path1, loader1); Assert.False(refA.Equals(null)); Assert.True(refA.Equals(refA)); Assert.True(refA.Equals(refB)); Assert.Equal(refA.GetHashCode(), refB.GetHashCode()); // paths are compared for exact equality, it's up to the host to normalize them: Assert.False(refA.Equals(new AnalyzerFileReference(path2, loader1))); // different loader: Assert.False(refA.Equals(new AnalyzerFileReference(path1, loader2))); // legacy overload: Assert.True(refA.Equals((AnalyzerReference)refA)); Assert.False(refA.Equals((AnalyzerReference?)null)); Assert.True(refA!.Equals((AnalyzerReference)refB)); Assert.True(refA.Equals(new TestAnalyzerReference(path1))); Assert.False(refA.Equals(new TestAnalyzerReference(path2))); } [Fact] public void TestMetadataParse() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var analyzerTypeNameMap = reference.GetAnalyzerTypeNameMap(); Assert.Equal(2, analyzerTypeNameMap.Keys.Count()); Assert.Equal(6, analyzerTypeNameMap[LanguageNames.CSharp].Count); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzerCS", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.TestAnalyzerCSVB", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzer", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedAnalyzer", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AbstractAnalyzer", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.OpenGenericAnalyzer`1", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.DoesNotContain("Microsoft.CodeAnalysis.UnitTests.Test.NotAnAnalyzer", analyzerTypeNameMap[LanguageNames.CSharp]); Assert.Equal(6, analyzerTypeNameMap[LanguageNames.VisualBasic].Count); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzerVB", analyzerTypeNameMap[LanguageNames.VisualBasic]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.TestAnalyzerCSVB", analyzerTypeNameMap[LanguageNames.VisualBasic]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzer", analyzerTypeNameMap[LanguageNames.VisualBasic]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedAnalyzer", analyzerTypeNameMap[LanguageNames.VisualBasic]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AbstractAnalyzer", analyzerTypeNameMap[LanguageNames.VisualBasic]); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.OpenGenericAnalyzer`1", analyzerTypeNameMap[LanguageNames.VisualBasic]); Assert.DoesNotContain("Microsoft.CodeAnalysis.UnitTests.Test.NotAnAnalyzer", analyzerTypeNameMap[LanguageNames.VisualBasic]); } [Fact] public void TestGetAnalyzersPerLanguage() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var analyzers = reference.GetAnalyzers(LanguageNames.CSharp); Assert.Equal(4, analyzers.Length); var analyzerNames = analyzers.Select(a => a.GetType().Name); Assert.Contains("TestAnalyzer", analyzerNames); Assert.Contains("TestAnalyzerCS", analyzerNames); Assert.Contains("TestAnalyzerCSVB", analyzerNames); Assert.Contains("NestedAnalyzer", analyzerNames); analyzers = reference.GetAnalyzers(LanguageNames.VisualBasic); analyzerNames = analyzers.Select(a => a.GetType().Name); Assert.Equal(4, analyzers.Length); Assert.Contains("TestAnalyzerVB", analyzerNames); Assert.Contains("TestAnalyzerCSVB", analyzerNames); Assert.Contains("TestAnalyzer", analyzerNames); Assert.Contains("NestedAnalyzer", analyzerNames); } [Fact] public void TestLoadErrors1() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); List<AnalyzerLoadFailureEventArgs> errors = new List<AnalyzerLoadFailureEventArgs>(); EventHandler<AnalyzerLoadFailureEventArgs> errorHandler = (o, e) => errors.Add(e); reference.AnalyzerLoadFailed += errorHandler; var builder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); reference.AddAnalyzers(builder, LanguageNames.CSharp); var analyzers = builder.ToImmutable(); reference.AnalyzerLoadFailed -= errorHandler; Assert.Equal(2, errors.Count); var failedTypes = errors.Where(e => e.ErrorCode == AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer).Select(e => e.TypeName); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.AbstractAnalyzer", failedTypes); Assert.Contains("Microsoft.CodeAnalysis.UnitTests.OpenGenericAnalyzer`1", failedTypes); } [Fact] public void TestLoadErrors2() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Path.Combine(TempRoot.Root, "random.dll")); List<AnalyzerLoadFailureEventArgs> errors = new List<AnalyzerLoadFailureEventArgs>(); EventHandler<AnalyzerLoadFailureEventArgs> errorHandler = (o, e) => errors.Add(e); reference.AnalyzerLoadFailed += errorHandler; var builder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); reference.AddAnalyzers(builder, LanguageNames.CSharp); var analyzers = builder.ToImmutable(); reference.AnalyzerLoadFailed -= errorHandler; Assert.Equal(1, errors.Count); Assert.Equal(AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer, errors.First().ErrorCode); } [Fact] public void TestLoadErrors3() { AnalyzerFileReference reference = CreateAnalyzerFileReference(_testFixture.Alpha.Path); List<AnalyzerLoadFailureEventArgs> errors = new List<AnalyzerLoadFailureEventArgs>(); EventHandler<AnalyzerLoadFailureEventArgs> errorHandler = (o, e) => errors.Add(e); reference.AnalyzerLoadFailed += errorHandler; var builder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); reference.AddAnalyzers(builder, LanguageNames.CSharp); var analyzers = builder.ToImmutable(); reference.AnalyzerLoadFailed -= errorHandler; Assert.Equal(0, errors.Count); } [Fact] [WorkItem(1029928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029928")] public void BadAnalyzerReference_DisplayName() { var directory = Temp.CreateDirectory(); var textFile = directory.CreateFile("Goo.txt").WriteAllText("I am the very model of a modern major general."); AnalyzerFileReference reference = CreateAnalyzerFileReference(textFile.Path); Assert.Equal(expected: "Goo", actual: reference.Display); } [Fact] public void ValidAnalyzerReference_DisplayName() { AnalyzerFileReference reference = CreateAnalyzerFileReference(_testFixture.Alpha.Path); Assert.Equal(expected: "Alpha", actual: reference.Display); } [Fact] [WorkItem(2781, "https://github.com/dotnet/roslyn/issues/2781")] [WorkItem(2782, "https://github.com/dotnet/roslyn/issues/2782")] public void ValidAnalyzerReference_Id() { AnalyzerFileReference reference = CreateAnalyzerFileReference(_testFixture.Alpha.Path); AssemblyIdentity.TryParseDisplayName("Alpha, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", out var expectedIdentity); Assert.Equal(expected: expectedIdentity, actual: reference.Id); } [Fact] [WorkItem(2781, "https://github.com/dotnet/roslyn/issues/2781")] [WorkItem(2782, "https://github.com/dotnet/roslyn/issues/2782")] public void BadAnalyzerReference_Id() { var directory = Temp.CreateDirectory(); var textFile = directory.CreateFile("Goo.txt").WriteAllText("I am the very model of a modern major general."); AnalyzerFileReference reference = CreateAnalyzerFileReference(textFile.Path); Assert.Equal(expected: "Goo", actual: reference.Id); } [Fact] [WorkItem(1032909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032909")] public void TestFailedLoadDoesntCauseNoAnalyzersWarning() { AnalyzerFileReference reference = CreateAnalyzerFileReference(_testFixture.FaultyAnalyzer.Path); List<AnalyzerLoadFailureEventArgs> errors = new List<AnalyzerLoadFailureEventArgs>(); EventHandler<AnalyzerLoadFailureEventArgs> errorHandler = (o, e) => errors.Add(e); reference.AnalyzerLoadFailed += errorHandler; var builder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); reference.AddAnalyzers(builder, LanguageNames.CSharp); var analyzers = builder.ToImmutable(); reference.AnalyzerLoadFailed -= errorHandler; Assert.Equal(1, errors.Count); Assert.Equal(AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer, errors.First().ErrorCode); } [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a framework targeting generator, which these are in desktop")] public void TestLoadGenerators() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var generators = reference.GetGeneratorsForAllLanguages(); var typeNames = generators.Select(g => g.GetGeneratorType().FullName); AssertEx.SetEqual(new[] { "Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", "Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", "Microsoft.CodeAnalysis.UnitTests.TestGenerator", "Microsoft.CodeAnalysis.UnitTests.BaseGenerator", "Microsoft.CodeAnalysis.UnitTests.SubClassedGenerator", "Microsoft.CodeAnalysis.UnitTests.ExplicitCSharpOnlyGenerator", "Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator", "Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", "Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", "Microsoft.CodeAnalysis.UnitTests.FSharpGenerator", "Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", "Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator" }, typeNames); } [ConditionalFact(typeof(CoreClrOnly))] public void TestLoadGeneratorsWithoutArgumentOnlyLoadsCSharp() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var generators = reference.GetGenerators(LanguageNames.CSharp); #pragma warning disable CS0618 // Type or member is obsolete var generators2 = reference.GetGenerators(); #pragma warning restore CS0618 // Type or member is obsolete Assert.Equal(generators, generators2); } [ConditionalFact(typeof(CoreClrOnly))] public void TestLoadCSharpGenerators() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var generators = reference.GetGenerators(LanguageNames.CSharp); var typeNames = generators.Select(g => g.GetGeneratorType().FullName); AssertEx.SetEqual(new[] { "Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", "Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", "Microsoft.CodeAnalysis.UnitTests.TestGenerator", "Microsoft.CodeAnalysis.UnitTests.BaseGenerator", "Microsoft.CodeAnalysis.UnitTests.SubClassedGenerator", "Microsoft.CodeAnalysis.UnitTests.ExplicitCSharpOnlyGenerator", "Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", "Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", "Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", "Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator" }, typeNames); } [ConditionalFact(typeof(CoreClrOnly))] public void TestLoadVisualBasicGenerators() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var generators = reference.GetGenerators(LanguageNames.VisualBasic); var typeNames = generators.Select(g => g.GetGeneratorType().FullName); AssertEx.SetEqual(new[] { "Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator", "Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", "Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", "Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", "Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator" }, typeNames); } // can't load a coreclr targeting generator on net framework / mono [ConditionalFact(typeof(CoreClrOnly))] public void TestGeneratorsCantTargetNetFramework() { var directory = Temp.CreateDirectory(); // core var errors = buildAndLoadGeneratorAndReturnAnyErrors(".NETCoreApp,Version=v5.0"); Assert.Empty(errors); // netstandard errors = buildAndLoadGeneratorAndReturnAnyErrors(".NETStandard,Version=v2.0"); Assert.Empty(errors); // no target errors = buildAndLoadGeneratorAndReturnAnyErrors(targetFramework: null); Assert.Empty(errors); // framework errors = buildAndLoadGeneratorAndReturnAnyErrors(".NETFramework,Version=v4.7.2"); Assert.Equal(2, errors.Count); Assert.Equal(AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework, errors.First().ErrorCode); List<AnalyzerLoadFailureEventArgs> buildAndLoadGeneratorAndReturnAnyErrors(string? targetFramework) { string targetFrameworkAttributeText = targetFramework is object ? $"[assembly: System.Runtime.Versioning.TargetFramework(\"{targetFramework}\")]" : string.Empty; string generatorSource = $@" using Microsoft.CodeAnalysis; {targetFrameworkAttributeText} [Generator] public class Generator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var directory = Temp.CreateDirectory(); var generatorPath = Path.Combine(directory.Path, $"generator_{targetFramework}.dll"); var compilation = CSharpCompilation.Create($"generator_{targetFramework}", new[] { CSharpSyntaxTree.ParseText(generatorSource) }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, new[] { MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly) }), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); compilation.VerifyDiagnostics(); var result = compilation.Emit(generatorPath); Assert.True(result.Success); AnalyzerFileReference reference = CreateAnalyzerFileReference(generatorPath); List<AnalyzerLoadFailureEventArgs> errors = new List<AnalyzerLoadFailureEventArgs>(); void errorHandler(object? o, AnalyzerLoadFailureEventArgs e) => errors.Add(e); reference.AnalyzerLoadFailed += errorHandler; var builder = ImmutableArray.CreateBuilder<ISourceGenerator>(); reference.AddGenerators(builder, LanguageNames.CSharp); reference.AnalyzerLoadFailed -= errorHandler; if (errors.Count > 0) { Assert.Empty(builder); } else { Assert.Single(builder); } return errors; } } [Fact] [WorkItem(52035, "https://github.com/dotnet/roslyn/issues/52035")] public void TestLoadedAnalyzerOrderIsDeterministic() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var csharpAnalyzers = reference.GetAnalyzers(LanguageNames.CSharp).Select(a => a.GetType().FullName).ToArray(); Assert.Equal(4, csharpAnalyzers.Length); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedAnalyzer", csharpAnalyzers[0]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzer", csharpAnalyzers[1]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzerCS", csharpAnalyzers[2]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestAnalyzerCSVB", csharpAnalyzers[3]); var vbAnalyzers = reference.GetAnalyzers(LanguageNames.VisualBasic).Select(a => a.GetType().FullName).ToArray(); Assert.Equal(4, vbAnalyzers.Length); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedAnalyzer", vbAnalyzers[0]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzer", vbAnalyzers[1]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzerVB", vbAnalyzers[2]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestAnalyzerCSVB", vbAnalyzers[3]); // analyzers return C#, then VB, including duplicates var allAnalyzers = reference.GetAnalyzersForAllLanguages().Select(a => a.GetType().FullName).ToArray(); Assert.Equal(8, allAnalyzers.Length); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedAnalyzer", allAnalyzers[0]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzer", allAnalyzers[1]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzerCS", allAnalyzers[2]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestAnalyzerCSVB", allAnalyzers[3]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedAnalyzer", allAnalyzers[4]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzer", allAnalyzers[5]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestAnalyzerVB", allAnalyzers[6]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestAnalyzerCSVB", allAnalyzers[7]); } [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a framework targeting generator, which these are in desktop")] [WorkItem(52035, "https://github.com/dotnet/roslyn/issues/52035")] public void TestLoadedGeneratorOrderIsDeterministic() { AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location); var csharpGenerators = reference.GetGenerators(LanguageNames.CSharp).Select(g => g.GetGeneratorType().FullName).ToArray(); Assert.Equal(10, csharpGenerators.Length); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", csharpGenerators[0]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", csharpGenerators[1]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.BaseGenerator", csharpGenerators[2]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", csharpGenerators[3]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.ExplicitCSharpOnlyGenerator", csharpGenerators[4]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.SubClassedGenerator", csharpGenerators[5]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestGenerator", csharpGenerators[6]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator", csharpGenerators[7]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", csharpGenerators[8]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", csharpGenerators[9]); var vbGenerators = reference.GetGenerators(LanguageNames.VisualBasic).Select(g => g.GetGeneratorType().FullName).ToArray(); Assert.Equal(5, vbGenerators.Length); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", vbGenerators[0]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator", vbGenerators[1]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", vbGenerators[2]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", vbGenerators[3]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator", vbGenerators[4]); // generators load in language order (C#, F#, VB), and *do not* include duplicates var allGenerators = reference.GetGeneratorsForAllLanguages().Select(g => g.GetGeneratorType().FullName).ToArray(); Assert.Equal(12, allGenerators.Length); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", allGenerators[0]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", allGenerators[1]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.BaseGenerator", allGenerators[2]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", allGenerators[3]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.ExplicitCSharpOnlyGenerator", allGenerators[4]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.SubClassedGenerator", allGenerators[5]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestGenerator", allGenerators[6]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator", allGenerators[7]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", allGenerators[8]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", allGenerators[9]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.FSharpGenerator", allGenerators[10]); Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator", allGenerators[11]); } // NOTE: the order in which these are emitted can change the test 'TestLoadedAnalyzerOrderIsDeterministic' // and other determinism tests in this file. // Ensure you do not re-arrange them alphabetically, as that will invalidate the tests, without // explicitly failing them [DiagnosticAnalyzer(LanguageNames.CSharp, new string[] { LanguageNames.VisualBasic })] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class TestAnalyzerCS : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } [DiagnosticAnalyzer(LanguageNames.VisualBasic, new string[] { })] public class TestAnalyzerVB : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } [Generator] public class TestGenerator : ISourceGenerator { public void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); public void Initialize(GeneratorInitializationContext context) => throw new NotImplementedException(); } public class SomeType { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class NestedAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } [Generator] public class NestedGenerator : ISourceGenerator { public void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); public void Initialize(GeneratorInitializationContext context) => throw new NotImplementedException(); } } } namespace Test { public class DiagnosticAnalyzer : Attribute { } [Test.DiagnosticAnalyzer] public class NotAnAnalyzer { } public class Generator : Attribute { } [Test.Generator] public class NotAGenerator { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class TestAnalyzerCSVB : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } public class TestAnalyzerNone { } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public abstract class AbstractAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class OpenGenericAnalyzer<T> : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } [Generator] public class TestGenerator : ISourceGenerator { public void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); public void Initialize(GeneratorInitializationContext context) => throw new NotImplementedException(); } public class TestGeneratorNoAttrib : ISourceGenerator { public void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); public void Initialize(GeneratorInitializationContext context) => throw new NotImplementedException(); } [Generator] public class BaseGenerator : ISourceGenerator { public virtual void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); public void Initialize(GeneratorInitializationContext context) => throw new NotImplementedException(); } [Generator] public class SubClassedGenerator : BaseGenerator { public override void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); } [Generator] public class NotAGenerator { } [Generator(LanguageNames.CSharp)] public class ExplicitCSharpOnlyGenerator : TestGenerator { } [Generator(LanguageNames.VisualBasic)] public class VisualBasicOnlyGenerator : TestGenerator { } [Generator(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class CSharpAndVisualBasicGenerator : TestGenerator { } [Generator(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class VisualBasicAndCSharpGenerator : TestGenerator { } [Generator(LanguageNames.FSharp)] public class FSharpGenerator : TestGenerator { } [Generator(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class TestIncrementalGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) => throw new NotImplementedException(); } public class TestIncrementalGeneratorWithNoAttrib : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) => throw new NotImplementedException(); } [Generator(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class TestSourceAndIncrementalGenerator : IIncrementalGenerator, ISourceGenerator { public void Execute(GeneratorExecutionContext context) => throw new NotImplementedException(); public void Initialize(IncrementalGeneratorInitializationContext context) => throw new NotImplementedException(); public void Initialize(GeneratorInitializationContext context) => throw new NotImplementedException(); } }
1
dotnet/roslyn
55,098
Use directory-scoped ALCs to load analyzers in .NET Core
Resolves #52177
RikkiGibson
2021-07-23T23:26:39Z
2021-08-23T19:01:28Z
e079a36f3ade7cda2a464e4fdcde0a11577fd1ea
99f45b7c174d1a2e9b6a1d810b4069600c80421d
Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177
./src/Compilers/Core/CodeAnalysisTest/AssemblyUtilitiesTests.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; using System.Reflection; using System.Text; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class AssemblyUtilitiesTests : TestBase { [Fact] public void FindAssemblySet_SingleAssembly() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var results = AssemblyUtilities.FindAssemblySet(alphaDll.Path); Assert.Equal(expected: 1, actual: results.Length); Assert.Equal(expected: alphaDll.Path, actual: results[0]); } [Fact] public void FindAssemblySet_TwoUnrelatedAssemblies() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var betaDll = directory.CreateFile("Beta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Beta); var results = AssemblyUtilities.FindAssemblySet(alphaDll.Path); Assert.Equal(expected: 1, actual: results.Length); Assert.Equal(expected: alphaDll.Path, actual: results[0]); } [Fact] public void FindAssemblySet_SimpleDependency() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var gammaDll = directory.CreateFile("Gamma.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Gamma); var results = AssemblyUtilities.FindAssemblySet(alphaDll.Path); Assert.Equal(expected: 2, actual: results.Length); Assert.Contains(alphaDll.Path, results, StringComparer.OrdinalIgnoreCase); Assert.Contains(gammaDll.Path, results, StringComparer.OrdinalIgnoreCase); } [Fact] public void FindAssemblySet_TransitiveDependencies() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var gammaDll = directory.CreateFile("Gamma.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Gamma); var deltaDll = directory.CreateFile("Delta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Delta); var results = AssemblyUtilities.FindAssemblySet(alphaDll.Path); Assert.Equal(expected: 3, actual: results.Length); Assert.Contains(alphaDll.Path, results, StringComparer.OrdinalIgnoreCase); Assert.Contains(gammaDll.Path, results, StringComparer.OrdinalIgnoreCase); Assert.Contains(deltaDll.Path, results, StringComparer.OrdinalIgnoreCase); } [Fact] public void ReadMVid() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var assembly = Assembly.Load(File.ReadAllBytes(alphaDll.Path)); var result = AssemblyUtilities.ReadMvid(alphaDll.Path); Assert.Equal(expected: assembly.ManifestModule.ModuleVersionId, actual: result); } [Fact] public void FindSatelliteAssemblies_None() { var directory = Temp.CreateDirectory(); var assemblyFile = directory.CreateFile("FakeAssembly.dll"); var results = AssemblyUtilities.FindSatelliteAssemblies(assemblyFile.Path); Assert.Equal(expected: 0, actual: results.Length); } [Fact] public void FindSatelliteAssemblies_DoesNotIncludeFileInSameDirectory() { var directory = Temp.CreateDirectory(); var assemblyFile = directory.CreateFile("FakeAssembly.dll"); var satelliteFile = directory.CreateFile("FakeAssembly.resources.dll"); var results = AssemblyUtilities.FindSatelliteAssemblies(assemblyFile.Path); Assert.Equal(expected: 0, actual: results.Length); } [Fact] public void FindSatelliteAssemblies_OneLevelDown() { var directory = Temp.CreateDirectory(); var assemblyFile = directory.CreateFile("FakeAssembly.dll"); var satelliteFile = directory.CreateDirectory("de").CreateFile("FakeAssembly.resources.dll"); var results = AssemblyUtilities.FindSatelliteAssemblies(assemblyFile.Path); Assert.Equal(expected: 1, actual: results.Length); Assert.Equal(expected: satelliteFile.Path, actual: results[0], comparer: StringComparer.OrdinalIgnoreCase); } [Fact] public void FindSatelliteAssemblies_TwoLevelsDown() { var directory = Temp.CreateDirectory(); var assemblyFile = directory.CreateFile("FakeAssembly.dll"); var satelliteFile = directory.CreateDirectory("de").CreateDirectory("FakeAssembly.resources").CreateFile("FakeAssembly.resources.dll"); var results = AssemblyUtilities.FindSatelliteAssemblies(assemblyFile.Path); Assert.Equal(expected: 1, actual: results.Length); Assert.Equal(expected: satelliteFile.Path, actual: results[0], comparer: StringComparer.OrdinalIgnoreCase); } [Fact] public void FindSatelliteAssemblies_MultipleAssemblies() { var directory = Temp.CreateDirectory(); var assemblyFile = directory.CreateFile("FakeAssembly.dll"); var satelliteFileDE = directory.CreateDirectory("de").CreateFile("FakeAssembly.resources.dll"); var satelliteFileFR = directory.CreateDirectory("fr").CreateFile("FakeAssembly.resources.dll"); var results = AssemblyUtilities.FindSatelliteAssemblies(assemblyFile.Path); Assert.Equal(expected: 2, actual: results.Length); Assert.Contains(satelliteFileDE.Path, results, StringComparer.OrdinalIgnoreCase); Assert.Contains(satelliteFileFR.Path, results, StringComparer.OrdinalIgnoreCase); } [Fact] public void FindSatelliteAssemblies_WrongIntermediateDirectoryName() { var directory = Temp.CreateDirectory(); var assemblyFile = directory.CreateFile("FakeAssembly.dll"); var satelliteFile = directory.CreateDirectory("de").CreateDirectory("OtherAssembly.resources").CreateFile("FakeAssembly.resources.dll"); var results = AssemblyUtilities.FindSatelliteAssemblies(assemblyFile.Path); Assert.Equal(expected: 0, actual: results.Length); } [Fact] public void IdentifyMissingDependencies_OnlyMscorlibMissing() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var gammaDll = directory.CreateFile("Gamma.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Gamma); var deltaDll = directory.CreateFile("Delta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Delta); var results = AssemblyUtilities.IdentifyMissingDependencies(alphaDll.Path, new[] { alphaDll.Path, gammaDll.Path, deltaDll.Path }); Assert.Equal(expected: 1, actual: results.Length); Assert.Equal(expected: "mscorlib", actual: results[0].Name); } [Fact] public void IdentifyMissingDependencies_MultipleMissing() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var results = AssemblyUtilities.IdentifyMissingDependencies(alphaDll.Path, new[] { alphaDll.Path }).Select(identity => identity.Name); Assert.Equal(expected: 2, actual: results.Count()); Assert.Contains("mscorlib", results); Assert.Contains("Gamma", results); } [Fact] public void GetAssemblyIdentity() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var result = AssemblyUtilities.GetAssemblyIdentity(alphaDll.Path); Assert.Equal(expected: "Alpha", actual: result.Name); } } }
// 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; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { [Collection(AssemblyLoadTestFixtureCollection.Name)] public class AssemblyUtilitiesTests : TestBase { private readonly AssemblyLoadTestFixture _testFixture; public AssemblyUtilitiesTests(AssemblyLoadTestFixture testFixture) { _testFixture = testFixture; } [Fact] public void FindAssemblySet_SingleAssembly() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CopyFile(_testFixture.Alpha.Path); var results = AssemblyUtilities.FindAssemblySet(alphaDll.Path); AssertEx.SetEqual(new[] { alphaDll.Path }, results); } [Fact] public void FindAssemblySet_TwoUnrelatedAssemblies() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CopyFile(_testFixture.Alpha.Path); var betaDll = directory.CopyFile(_testFixture.Beta.Path); var results = AssemblyUtilities.FindAssemblySet(alphaDll.Path); AssertEx.SetEqual(new[] { alphaDll.Path }, results); } [Fact] public void FindAssemblySet_SimpleDependency() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CopyFile(_testFixture.Alpha.Path); var gammaDll = directory.CopyFile(_testFixture.Gamma.Path); var results = AssemblyUtilities.FindAssemblySet(alphaDll.Path); AssertEx.SetEqual(new[] { alphaDll.Path, gammaDll.Path }, results, StringComparer.OrdinalIgnoreCase); } [Fact] public void FindAssemblySet_TransitiveDependencies() { var results = AssemblyUtilities.FindAssemblySet(_testFixture.Alpha.Path); AssertEx.SetEqual(new[] { _testFixture.Alpha.Path, _testFixture.Gamma.Path, _testFixture.Delta1.Path }, results, StringComparer.OrdinalIgnoreCase); } [Fact] public void ReadMVid() { var assembly = Assembly.Load(File.ReadAllBytes(_testFixture.Alpha.Path)); var result = AssemblyUtilities.ReadMvid(_testFixture.Alpha.Path); Assert.Equal(expected: assembly.ManifestModule.ModuleVersionId, actual: result); } [Fact] public void FindSatelliteAssemblies_None() { var directory = Temp.CreateDirectory(); var assemblyFile = directory.CreateFile("FakeAssembly.dll"); var results = AssemblyUtilities.FindSatelliteAssemblies(assemblyFile.Path); Assert.Empty(results); } [Fact] public void FindSatelliteAssemblies_DoesNotIncludeFileInSameDirectory() { var directory = Temp.CreateDirectory(); var assemblyFile = directory.CreateFile("FakeAssembly.dll"); var satelliteFile = directory.CreateFile("FakeAssembly.resources.dll"); var results = AssemblyUtilities.FindSatelliteAssemblies(assemblyFile.Path); Assert.Empty(results); } [Fact] public void FindSatelliteAssemblies_OneLevelDown() { var directory = Temp.CreateDirectory(); var assemblyFile = directory.CreateFile("FakeAssembly.dll"); var satelliteFile = directory.CreateDirectory("de").CreateFile("FakeAssembly.resources.dll"); var results = AssemblyUtilities.FindSatelliteAssemblies(assemblyFile.Path); AssertEx.SetEqual(new[] { satelliteFile.Path }, results, StringComparer.OrdinalIgnoreCase); } [Fact] public void FindSatelliteAssemblies_TwoLevelsDown() { var directory = Temp.CreateDirectory(); var assemblyFile = directory.CreateFile("FakeAssembly.dll"); var satelliteFile = directory.CreateDirectory("de").CreateDirectory("FakeAssembly.resources").CreateFile("FakeAssembly.resources.dll"); var results = AssemblyUtilities.FindSatelliteAssemblies(assemblyFile.Path); AssertEx.SetEqual(new[] { satelliteFile.Path }, results, StringComparer.OrdinalIgnoreCase); } [Fact] public void FindSatelliteAssemblies_MultipleAssemblies() { var directory = Temp.CreateDirectory(); var assemblyFile = directory.CreateFile("FakeAssembly.dll"); var satelliteFileDE = directory.CreateDirectory("de").CreateFile("FakeAssembly.resources.dll"); var satelliteFileFR = directory.CreateDirectory("fr").CreateFile("FakeAssembly.resources.dll"); var results = AssemblyUtilities.FindSatelliteAssemblies(assemblyFile.Path); AssertEx.SetEqual(new[] { satelliteFileDE.Path, satelliteFileFR.Path }, results, StringComparer.OrdinalIgnoreCase); } [Fact] public void FindSatelliteAssemblies_WrongIntermediateDirectoryName() { var directory = Temp.CreateDirectory(); var assemblyFile = directory.CreateFile("FakeAssembly.dll"); var satelliteFile = directory.CreateDirectory("de").CreateDirectory("OtherAssembly.resources").CreateFile("FakeAssembly.resources.dll"); var results = AssemblyUtilities.FindSatelliteAssemblies(assemblyFile.Path); Assert.Equal(expected: 0, actual: results.Length); } [Fact] public void IdentifyMissingDependencies_OnlyNetstandardMissing() { var results = AssemblyUtilities.IdentifyMissingDependencies(_testFixture.Alpha.Path, new[] { _testFixture.Alpha.Path, _testFixture.Gamma.Path, _testFixture.Delta1.Path }); Assert.Equal(expected: 1, actual: results.Length); Assert.Equal(expected: "netstandard", actual: results[0].Name); } [Fact] public void IdentifyMissingDependencies_MultipleMissing() { var results = AssemblyUtilities.IdentifyMissingDependencies(_testFixture.Alpha.Path, new[] { _testFixture.Alpha.Path }).Select(identity => identity.Name); AssertEx.SetEqual(new[] { "netstandard", "Gamma" }, results); } [Fact] public void GetAssemblyIdentity() { var result = AssemblyUtilities.GetAssemblyIdentity(_testFixture.Alpha.Path); Assert.Equal(expected: "Alpha", actual: result.Name); } } }
1
dotnet/roslyn
55,098
Use directory-scoped ALCs to load analyzers in .NET Core
Resolves #52177
RikkiGibson
2021-07-23T23:26:39Z
2021-08-23T19:01:28Z
e079a36f3ade7cda2a464e4fdcde0a11577fd1ea
99f45b7c174d1a2e9b6a1d810b4069600c80421d
Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177
./src/Compilers/Core/CodeAnalysisTest/DefaultAnalyzerAssemblyLoaderTests.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.Reflection; using System.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase { [Fact] public void AddDependencyLocationThrowsOnNull() { var loader = new DefaultAnalyzerAssemblyLoader(); Assert.Throws<ArgumentNullException>("fullPath", () => loader.AddDependencyLocation(null)); Assert.Throws<ArgumentException>("fullPath", () => loader.AddDependencyLocation("a")); } [Fact] public void ThrowsForMissingFile() { var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".dll"); var loader = new DefaultAnalyzerAssemblyLoader(); Assert.ThrowsAny<Exception>(() => loader.LoadFromPath(path)); } [Fact] public void BasicLoad() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var loader = new DefaultAnalyzerAssemblyLoader(); Assembly alpha = loader.LoadFromPath(alphaDll.Path); Assert.NotNull(alpha); } [Fact] public void AssemblyLoading() { StringBuilder sb = new StringBuilder(); var directory = Temp.CreateDirectory(); var alphaDll = Temp.CreateDirectory().CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var betaDll = Temp.CreateDirectory().CreateFile("Beta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Beta); var gammaDll = Temp.CreateDirectory().CreateFile("Gamma.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Gamma); var deltaDll = Temp.CreateDirectory().CreateFile("Delta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Delta); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(alphaDll.Path); loader.AddDependencyLocation(betaDll.Path); loader.AddDependencyLocation(gammaDll.Path); loader.AddDependencyLocation(deltaDll.Path); Assembly alpha = loader.LoadFromPath(alphaDll.Path); var a = alpha.CreateInstance("Alpha.A"); a.GetType().GetMethod("Write").Invoke(a, new object[] { sb, "Test A" }); Assembly beta = loader.LoadFromPath(betaDll.Path); var b = beta.CreateInstance("Beta.B"); b.GetType().GetMethod("Write").Invoke(b, new object[] { sb, "Test B" }); var expected = @"Delta: Gamma: Alpha: Test A Delta: Gamma: Beta: Test B "; var actual = sb.ToString(); Assert.Equal(expected, actual); } } }
// 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; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.UnitTests { [CollectionDefinition(Name)] public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture> { public const string Name = nameof(AssemblyLoadTestFixtureCollection); private AssemblyLoadTestFixtureCollection() { } } [Collection(AssemblyLoadTestFixtureCollection.Name)] public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel); private readonly ITestOutputHelper _output; private readonly AssemblyLoadTestFixture _testFixture; public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture) { _output = output; _testFixture = testFixture; } [Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")] public void LoadWithDependency() { var analyzerDependencyFile = _testFixture.AnalyzerDependency; var analyzerMainFile = _testFixture.AnalyzerWithDependency; var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(analyzerDependencyFile.Path); var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader); analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader); analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages(); Assert.Equal(1, analyzers.Length); Assert.Equal("TestAnalyzer", analyzers[0].ToString()); Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length); Assert.NotNull(analyzerDependencyReference.GetAssembly()); } [Fact] public void AddDependencyLocationThrowsOnNull() { var loader = new DefaultAnalyzerAssemblyLoader(); Assert.Throws<ArgumentNullException>("fullPath", () => loader.AddDependencyLocation(null)); Assert.Throws<ArgumentException>("fullPath", () => loader.AddDependencyLocation("a")); } [Fact] public void ThrowsForMissingFile() { var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".dll"); var loader = new DefaultAnalyzerAssemblyLoader(); Assert.ThrowsAny<Exception>(() => loader.LoadFromPath(path)); } [Fact] public void BasicLoad() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); Assert.NotNull(alpha); } [Fact] public void AssemblyLoading() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); var a = alpha.CreateInstance("Alpha.A")!; a.GetType().GetMethod("Write")!.Invoke(a, new object[] { sb, "Test A" }); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; b.GetType().GetMethod("Write")!.Invoke(b, new object[] { sb, "Test B" }); var expected = @"Delta: Gamma: Alpha: Test A Delta: Gamma: Beta: Test B "; var actual = sb.ToString(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_AssemblyLocationNotAdded() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assert.Throws<FileNotFoundException>(() => loader.LoadFromPath(_testFixture.Beta.Path)); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_DependencyLocationNotAdded() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); // We don't pass Alpha's path to AddDependencyLocation here, and therefore expect // calling Beta.B.Write to fail. loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; var writeMethod = b.GetType().GetMethod("Write")!; var exception = Assert.Throws<TargetInvocationException>( () => writeMethod.Invoke(b, new object[] { sb, "Test B" })); Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException); var actual = sb.ToString(); Assert.Equal(@"", actual); } [Fact] public void AssemblyLoading_MultipleVersions() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(2, alcs.Length); Assert.Equal(new[] { ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) }, alcs[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); Assert.Equal(new[] { ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path) }, alcs[1].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MultipleLoaders() { StringBuilder sb = new StringBuilder(); var loader1 = new DefaultAnalyzerAssemblyLoader(); loader1.AddDependencyLocation(_testFixture.Gamma.Path); loader1.AddDependencyLocation(_testFixture.Delta1.Path); var loader2 = new DefaultAnalyzerAssemblyLoader(); loader2.AddDependencyLocation(_testFixture.Epsilon.Path); loader2.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1); Assert.Equal(1, alcs1.Length); Assert.Equal(new[] { ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) }, alcs1[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2); Assert.Equal(1, alcs2.Length); Assert.Equal(new[] { ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path) }, alcs2[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MissingVersion() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; var eWrite = e.GetType().GetMethod("Write")!; var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { var exception = Assert.Throws<TargetInvocationException>(() => eWrite.Invoke(e, new object[] { sb, "Test E" })); Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException); } else { eWrite.Invoke(e, new object[] { sb, "Test E" }); Assert.Equal( @"Delta: Gamma: Test G ", actual); } } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; if (ExecutionConditionUtil.IsCoreClr) { var ex = Assert.ThrowsAny<Exception>(() => analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb })); Assert.True(ex is MissingMethodException or TargetInvocationException, $@"Unexpected exception type: ""{ex.GetType()}"""); } else { analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal("42", sb.ToString()); } } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal(ExecutionConditionUtil.IsCoreClr ? "1" : "42", sb.ToString()); } [ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))] public void AssemblyLoading_NativeDependency() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path); var analyzer = analyzerAssembly.CreateInstance("Class1")!; var result = analyzer.GetType().GetMethod("GetFileAttributes")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path }); Assert.Equal(0, Marshal.GetLastWin32Error()); Assert.Equal(FileAttributes.Archive, (FileAttributes)result!); } #if NETCOREAPP [Fact] public void VerifyCompilerAssemblySimpleNames() { var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly; var caReferences = caAssembly.GetReferencedAssemblies(); var allReferenceSimpleNames = ArrayBuilder<string>.GetInstance(); allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in caReferences) { allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException()); } var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly; allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException()); var csReferences = csAssembly.GetReferencedAssemblies(); foreach (var reference in csReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly; var vbReferences = vbAssembly.GetReferencedAssemblies(); allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in vbReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames)) { allReferenceSimpleNames.Sort(); var allNames = string.Join(",\r\n ", allReferenceSimpleNames.Select(name => $@"""{name}""")); _output.WriteLine(" internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames ="); _output.WriteLine(" ImmutableHashSet.Create("); _output.WriteLine(" StringComparer.OrdinalIgnoreCase,"); _output.WriteLine($" {allNames});"); allReferenceSimpleNames.Free(); Assert.True(false, $"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it."); } else { allReferenceSimpleNames.Free(); } } #endif } }
1
dotnet/roslyn
55,098
Use directory-scoped ALCs to load analyzers in .NET Core
Resolves #52177
RikkiGibson
2021-07-23T23:26:39Z
2021-08-23T19:01:28Z
e079a36f3ade7cda2a464e4fdcde0a11577fd1ea
99f45b7c174d1a2e9b6a1d810b4069600c80421d
Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177
./src/Compilers/Core/CodeAnalysisTest/ShadowCopyAnalyzerAssemblyLoaderTests.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.Immutable; using System.IO; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public sealed class ShadowCopyAnalyzerAssemblyLoaderTests : TestBase { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel); [Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")] public void LoadWithDependency() { var directory = Temp.CreateDirectory(); var immutable = directory.CopyFile(typeof(ImmutableArray).Assembly.Location); var microsoftCodeAnalysis = directory.CopyFile(typeof(DiagnosticAnalyzer).Assembly.Location); var analyzerDependencyFile = CreateAnalyzerDependency(); var analyzerMainFile = CreateMainAnalyzerWithDependency(analyzerDependencyFile); var loader = new ShadowCopyAnalyzerAssemblyLoader(Path.Combine(directory.Path, "AnalyzerAssemblyLoader")); var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader); analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception.Message); var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader); analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception.Message); var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages(); Assert.Equal(1, analyzers.Length); Assert.Equal("TestAnalyzer", analyzers[0].ToString()); Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length); Assert.NotNull(analyzerDependencyReference.GetAssembly()); TempFile CreateAnalyzerDependency() { var analyzerDependencySource = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; public abstract class AbstractTestAnalyzer : DiagnosticAnalyzer { protected static string SomeString = nameof(SomeString); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } }"; var analyzerDependencyCompilation = CSharpCompilation.Create( "AnalyzerDependency", new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerDependencySource) }, new MetadataReference[] { TestMetadata.NetStandard20.mscorlib, TestMetadata.NetStandard20.netstandard, TestMetadata.NetStandard20.SystemRuntime, MetadataReference.CreateFromFile(immutable.Path), MetadataReference.CreateFromFile(microsoftCodeAnalysis.Path) }, s_dllWithMaxWarningLevel); return directory.CreateDirectory("AnalyzerDependency").CreateFile("AnalyzerDependency.dll").WriteAllBytes(analyzerDependencyCompilation.EmitToArray()); } TempFile CreateMainAnalyzerWithDependency(TempFile analyzerDependency) { var analyzerMainSource = @" using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class TestAnalyzer : AbstractTestAnalyzer { private static string SomeString2 = AbstractTestAnalyzer.SomeString; }"; var analyzerMainCompilation = CSharpCompilation.Create( "AnalyzerMain", new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerMainSource) }, new MetadataReference[] { TestMetadata.NetStandard20.mscorlib, TestMetadata.NetStandard20.netstandard, TestMetadata.NetStandard20.SystemRuntime, MetadataReference.CreateFromFile(immutable.Path), MetadataReference.CreateFromFile(microsoftCodeAnalysis.Path), MetadataReference.CreateFromFile(analyzerDependency.Path) }, s_dllWithMaxWarningLevel); return directory.CreateDirectory("AnalyzerMain").CreateFile("AnalyzerMain.dll").WriteAllBytes(analyzerMainCompilation.EmitToArray()); } } } }
// 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.IO; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { [Collection(AssemblyLoadTestFixtureCollection.Name)] public sealed class ShadowCopyAnalyzerAssemblyLoaderTests : TestBase { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel); private readonly AssemblyLoadTestFixture _testFixture; public ShadowCopyAnalyzerAssemblyLoaderTests(AssemblyLoadTestFixture testFixture) { _testFixture = testFixture; } [Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")] public void LoadWithDependency() { var analyzerDependencyFile = _testFixture.AnalyzerDependency; var analyzerMainFile = _testFixture.AnalyzerWithDependency; var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(analyzerDependencyFile.Path); var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader); analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader); analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages(); Assert.Equal(1, analyzers.Length); Assert.Equal("TestAnalyzer", analyzers[0].ToString()); Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length); Assert.NotNull(analyzerDependencyReference.GetAssembly()); } [Fact] public void AssemblyLoading_MultipleVersions() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G"); g!.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E"); e!.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } } }
1
dotnet/roslyn
55,098
Use directory-scoped ALCs to load analyzers in .NET Core
Resolves #52177
RikkiGibson
2021-07-23T23:26:39Z
2021-08-23T19:01:28Z
e079a36f3ade7cda2a464e4fdcde0a11577fd1ea
99f45b7c174d1a2e9b6a1d810b4069600c80421d
Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerAssemblyLoader.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.Reflection; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract class AnalyzerAssemblyLoader : IAnalyzerAssemblyLoader { private readonly object _guard = new(); // lock _guard to read/write private readonly Dictionary<string, Assembly> _loadedAssembliesByPath = new(); private readonly Dictionary<string, AssemblyIdentity> _loadedAssemblyIdentitiesByPath = new(); private readonly Dictionary<AssemblyIdentity, Assembly> _loadedAssembliesByIdentity = new(); // maps file name to a full path (lock _guard to read/write): private readonly Dictionary<string, HashSet<string>> _knownAssemblyPathsBySimpleName = new(StringComparer.OrdinalIgnoreCase); protected abstract Assembly LoadFromPathImpl(string fullPath); #region Public API public void AddDependencyLocation(string fullPath) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); string simpleName = PathUtilities.GetFileName(fullPath, includeExtension: false); lock (_guard) { if (!_knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths)) { paths = new HashSet<string>(PathUtilities.Comparer); _knownAssemblyPathsBySimpleName.Add(simpleName, paths); } paths.Add(fullPath); } } public Assembly LoadFromPath(string fullPath) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); return LoadFromPathUnchecked(fullPath); } #endregion private Assembly LoadFromPathUnchecked(string fullPath) { return LoadFromPathUncheckedCore(fullPath); } private Assembly LoadFromPathUncheckedCore(string fullPath, AssemblyIdentity identity = null) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); // Check if we have already loaded an assembly with the same identity or from the given path. Assembly loadedAssembly = null; lock (_guard) { if (_loadedAssembliesByPath.TryGetValue(fullPath, out var existingAssembly)) { loadedAssembly = existingAssembly; } else { identity ??= GetOrAddAssemblyIdentity(fullPath); if (identity != null && _loadedAssembliesByIdentity.TryGetValue(identity, out existingAssembly)) { loadedAssembly = existingAssembly; } } } // Otherwise, load the assembly. if (loadedAssembly == null) { loadedAssembly = LoadFromPathImpl(fullPath); } // Add the loaded assembly to both path and identity cache. return AddToCache(loadedAssembly, fullPath, identity); } private Assembly AddToCache(Assembly assembly, string fullPath, AssemblyIdentity identity) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); Debug.Assert(assembly != null); identity = AddToCache(fullPath, identity ?? AssemblyIdentity.FromAssemblyDefinition(assembly)); Debug.Assert(identity != null); lock (_guard) { // The same assembly may be loaded from two different full paths (e.g. when loaded from GAC, etc.), // or another thread might have loaded the assembly after we checked above. if (_loadedAssembliesByIdentity.TryGetValue(identity, out var existingAssembly)) { assembly = existingAssembly; } else { _loadedAssembliesByIdentity.Add(identity, assembly); } // An assembly file might be replaced by another file with a different identity. // Last one wins. _loadedAssembliesByPath[fullPath] = assembly; return assembly; } } private AssemblyIdentity GetOrAddAssemblyIdentity(string fullPath) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); lock (_guard) { if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity)) { return existingIdentity; } } var identity = AssemblyIdentityUtils.TryGetAssemblyIdentity(fullPath); return AddToCache(fullPath, identity); } private AssemblyIdentity AddToCache(string fullPath, AssemblyIdentity identity) { lock (_guard) { if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity) && existingIdentity != null) { identity = existingIdentity; } else { _loadedAssemblyIdentitiesByPath[fullPath] = identity; } } return identity; } public Assembly Load(string displayName) { if (!AssemblyIdentity.TryParseDisplayName(displayName, out var requestedIdentity)) { return null; } ImmutableArray<string> candidatePaths; lock (_guard) { // First, check if this loader already loaded the requested assembly: if (_loadedAssembliesByIdentity.TryGetValue(requestedIdentity, out var existingAssembly)) { return existingAssembly; } // Second, check if an assembly file of the same simple name was registered with the loader: if (!_knownAssemblyPathsBySimpleName.TryGetValue(requestedIdentity.Name, out var pathList)) { return null; } Debug.Assert(pathList.Count > 0); candidatePaths = pathList.ToImmutableArray(); } // Multiple assemblies of the same simple name but different identities might have been registered. // Load the one that matches the requested identity (if any). foreach (var candidatePath in candidatePaths) { var candidateIdentity = GetOrAddAssemblyIdentity(candidatePath); if (requestedIdentity.Equals(candidateIdentity)) { return LoadFromPathUncheckedCore(candidatePath, candidateIdentity); } } 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract class AnalyzerAssemblyLoader : IAnalyzerAssemblyLoader { private readonly object _guard = new(); // lock _guard to read/write private readonly Dictionary<string, Assembly> _loadedAssembliesByPath = new(); private readonly Dictionary<string, AssemblyIdentity> _loadedAssemblyIdentitiesByPath = new(); private readonly Dictionary<AssemblyIdentity, Assembly> _loadedAssembliesByIdentity = new(); // maps file name to a full path (lock _guard to read/write): private readonly Dictionary<string, HashSet<string>> _knownAssemblyPathsBySimpleName = new(StringComparer.OrdinalIgnoreCase); protected abstract Assembly LoadFromPathImpl(string fullPath); #region Public API public void AddDependencyLocation(string fullPath) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); string simpleName = PathUtilities.GetFileName(fullPath, includeExtension: false); lock (_guard) { if (!_knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths)) { paths = new HashSet<string>(PathUtilities.Comparer); _knownAssemblyPathsBySimpleName.Add(simpleName, paths); } paths.Add(fullPath); } } public Assembly LoadFromPath(string fullPath) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); return LoadFromPathUnchecked(fullPath); } #endregion private Assembly LoadFromPathUnchecked(string fullPath) { return LoadFromPathUncheckedCore(fullPath); } private Assembly LoadFromPathUncheckedCore(string fullPath, AssemblyIdentity identity = null) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); // Check if we have already loaded an assembly with the same identity or from the given path. Assembly loadedAssembly = null; lock (_guard) { if (_loadedAssembliesByPath.TryGetValue(fullPath, out var existingAssembly)) { loadedAssembly = existingAssembly; } else { identity ??= GetOrAddAssemblyIdentity(fullPath); if (identity != null && _loadedAssembliesByIdentity.TryGetValue(identity, out existingAssembly)) { loadedAssembly = existingAssembly; } } } // Otherwise, load the assembly. if (loadedAssembly == null) { loadedAssembly = LoadFromPathImpl(fullPath); } // Add the loaded assembly to both path and identity cache. return AddToCache(loadedAssembly, fullPath, identity); } private Assembly AddToCache(Assembly assembly, string fullPath, AssemblyIdentity identity) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); Debug.Assert(assembly != null); identity = AddToCache(fullPath, identity ?? AssemblyIdentity.FromAssemblyDefinition(assembly)); Debug.Assert(identity != null); lock (_guard) { // The same assembly may be loaded from two different full paths (e.g. when loaded from GAC, etc.), // or another thread might have loaded the assembly after we checked above. if (_loadedAssembliesByIdentity.TryGetValue(identity, out var existingAssembly)) { assembly = existingAssembly; } else { _loadedAssembliesByIdentity.Add(identity, assembly); } // An assembly file might be replaced by another file with a different identity. // Last one wins. _loadedAssembliesByPath[fullPath] = assembly; return assembly; } } private AssemblyIdentity GetOrAddAssemblyIdentity(string fullPath) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); lock (_guard) { if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity)) { return existingIdentity; } } var identity = AssemblyIdentityUtils.TryGetAssemblyIdentity(fullPath); return AddToCache(fullPath, identity); } private AssemblyIdentity AddToCache(string fullPath, AssemblyIdentity identity) { lock (_guard) { if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity) && existingIdentity != null) { identity = existingIdentity; } else { _loadedAssemblyIdentitiesByPath[fullPath] = identity; } } return identity; } #nullable enable protected bool IsKnownDependencyLocation(string fullPath) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); var simpleName = PathUtilities.GetFileName(fullPath, includeExtension: false); if (!_knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths)) { return false; } if (!paths.Contains(fullPath)) { return false; } return true; } /// <summary> /// When overridden in a derived class, allows substituting an assembly path after we've /// identified the context to load an assembly in, but before the assembly is actually /// loaded from disk. /// </summary> protected virtual string GetPathToLoad(string fullPath) { return fullPath; } #nullable disable public Assembly Load(string displayName) { if (!AssemblyIdentity.TryParseDisplayName(displayName, out var requestedIdentity)) { return null; } ImmutableArray<string> candidatePaths; lock (_guard) { // First, check if this loader already loaded the requested assembly: if (_loadedAssembliesByIdentity.TryGetValue(requestedIdentity, out var existingAssembly)) { return existingAssembly; } // Second, check if an assembly file of the same simple name was registered with the loader: if (!_knownAssemblyPathsBySimpleName.TryGetValue(requestedIdentity.Name, out var pathList)) { return null; } Debug.Assert(pathList.Count > 0); candidatePaths = pathList.ToImmutableArray(); } // Multiple assemblies of the same simple name but different identities might have been registered. // Load the one that matches the requested identity (if any). foreach (var candidatePath in candidatePaths) { var candidateIdentity = GetOrAddAssemblyIdentity(candidatePath); if (requestedIdentity.Equals(candidateIdentity)) { return LoadFromPathUncheckedCore(candidatePath, candidateIdentity); } } return null; } } }
1
dotnet/roslyn
55,098
Use directory-scoped ALCs to load analyzers in .NET Core
Resolves #52177
RikkiGibson
2021-07-23T23:26:39Z
2021-08-23T19:01:28Z
e079a36f3ade7cda2a464e4fdcde0a11577fd1ea
99f45b7c174d1a2e9b6a1d810b4069600c80421d
Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Core.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 #if NETCOREAPP using System.Diagnostics; using System.Reflection; using System.Runtime.Loader; namespace Microsoft.CodeAnalysis { internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { private AssemblyLoadContext _loadContext; protected override Assembly LoadFromPathImpl(string fullPath) { //.NET Native doesn't support AssemblyLoadContext.GetLoadContext. // Initializing the _loadContext in the .ctor would cause // .NET Native builds to fail because the .ctor is called. // However, LoadFromPathImpl is never called in .NET Native, so // we do a lazy initialization here to make .NET Native builds happy. if (_loadContext == null) { AssemblyLoadContext loadContext = AssemblyLoadContext.GetLoadContext(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly); if (System.Threading.Interlocked.CompareExchange(ref _loadContext, loadContext, null) == null) { _loadContext.Resolving += (context, name) => { Debug.Assert(ReferenceEquals(context, _loadContext)); return Load(name.FullName); }; } } return LoadImpl(fullPath); } protected virtual Assembly LoadImpl(string fullPath) => _loadContext.LoadFromAssemblyPath(fullPath); } } #endif
// 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. #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; namespace Microsoft.CodeAnalysis { internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { /// <summary> /// <p>Typically a user analyzer has a reference to the compiler and some of the compiler's /// dependencies such as System.Collections.Immutable. For the analyzer to correctly /// interoperate with the compiler that created it, we need to ensure that we always use the /// compiler's version of a given assembly over the analyzer's version.</p> /// /// <p>If we neglect to do this, then in the case where the user ships the compiler or its /// dependencies in the analyzer's bin directory, we could end up loading a separate /// instance of those assemblies in the process of loading the analyzer, which will surface /// as a failure to load the analyzer.</p> /// </summary> internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames = ImmutableHashSet.Create( StringComparer.OrdinalIgnoreCase, "Microsoft.CodeAnalysis", "Microsoft.CodeAnalysis.CSharp", "Microsoft.CodeAnalysis.VisualBasic", "System.Collections", "System.Collections.Concurrent", "System.Collections.Immutable", "System.Console", "System.Diagnostics.Debug", "System.Diagnostics.StackTrace", "System.IO.Compression", "System.IO.FileSystem", "System.Linq", "System.Linq.Expressions", "System.Memory", "System.Reflection.Metadata", "System.Reflection.Primitives", "System.Resources.ResourceManager", "System.Runtime", "System.Runtime.CompilerServices.Unsafe", "System.Runtime.Extensions", "System.Runtime.InteropServices", "System.Runtime.Loader", "System.Runtime.Numerics", "System.Runtime.Serialization.Primitives", "System.Security.Cryptography.Algorithms", "System.Security.Cryptography.Primitives", "System.Text.Encoding.CodePages", "System.Text.Encoding.Extensions", "System.Text.RegularExpressions", "System.Threading", "System.Threading.Tasks", "System.Threading.Tasks.Parallel", "System.Threading.Thread", "System.Threading.ThreadPool", "System.Xml.ReaderWriter", "System.Xml.XDocument", "System.Xml.XPath.XDocument"); private readonly object _guard = new object(); private readonly Dictionary<string, DirectoryLoadContext> _loadContextByDirectory = new Dictionary<string, DirectoryLoadContext>(StringComparer.Ordinal); protected override Assembly LoadFromPathImpl(string fullPath) { DirectoryLoadContext? loadContext; var fullDirectoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException(message: null, paramName: nameof(fullPath)); lock (_guard) { if (!_loadContextByDirectory.TryGetValue(fullDirectoryPath, out loadContext)) { loadContext = new DirectoryLoadContext(fullDirectoryPath, this); _loadContextByDirectory[fullDirectoryPath] = loadContext; } } var name = AssemblyName.GetAssemblyName(fullPath); return loadContext.LoadFromAssemblyName(name); } internal static class TestAccessor { public static AssemblyLoadContext[] GetOrderedLoadContexts(DefaultAnalyzerAssemblyLoader loader) { return loader._loadContextByDirectory.Values.OrderBy(v => v.Directory).ToArray(); } } private sealed class DirectoryLoadContext : AssemblyLoadContext { internal string Directory { get; } private readonly DefaultAnalyzerAssemblyLoader _loader; public DirectoryLoadContext(string directory, DefaultAnalyzerAssemblyLoader loader) { Directory = directory; _loader = loader; } protected override Assembly? Load(AssemblyName assemblyName) { var simpleName = assemblyName.Name!; if (CompilerAssemblySimpleNames.Contains(simpleName)) { // Delegate to the compiler's load context to load the compiler or anything // referenced by the compiler return null; } var assemblyPath = Path.Combine(Directory, simpleName + ".dll"); if (!_loader.IsKnownDependencyLocation(assemblyPath)) { // The analyzer didn't explicitly register this dependency. Most likely the // assembly we're trying to load here is netstandard or a similar framework // assembly. We assume that if that is not the case, then the parent ALC will // fail to load this. return null; } var pathToLoad = _loader.GetPathToLoad(assemblyPath); return LoadFromAssemblyPath(pathToLoad); } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { var assemblyPath = Path.Combine(Directory, unmanagedDllName + ".dll"); if (!_loader.IsKnownDependencyLocation(assemblyPath)) { return IntPtr.Zero; } var pathToLoad = _loader.GetPathToLoad(assemblyPath); return LoadUnmanagedDllFromPath(pathToLoad); } } } } #endif
1
dotnet/roslyn
55,098
Use directory-scoped ALCs to load analyzers in .NET Core
Resolves #52177
RikkiGibson
2021-07-23T23:26:39Z
2021-08-23T19:01:28Z
e079a36f3ade7cda2a464e4fdcde0a11577fd1ea
99f45b7c174d1a2e9b6a1d810b4069600c80421d
Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177
./src/Compilers/Core/Portable/DiagnosticAnalyzer/ShadowCopyAnalyzerAssemblyLoader.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.Reflection; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal sealed class ShadowCopyAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader { /// <summary> /// The base directory for shadow copies. Each instance of /// <see cref="ShadowCopyAnalyzerAssemblyLoader"/> gets its own /// subdirectory under this directory. This is also the starting point /// for scavenge operations. /// </summary> private readonly string _baseDirectory; internal readonly Task DeleteLeftoverDirectoriesTask; /// <summary> /// The directory where this instance of <see cref="ShadowCopyAnalyzerAssemblyLoader"/> /// will shadow-copy assemblies, and the mutex created to mark that the owner of it is still active. /// </summary> private readonly Lazy<(string directory, Mutex)> _shadowCopyDirectoryAndMutex; /// <summary> /// Used to generate unique names for per-assembly directories. Should be updated with <see cref="Interlocked.Increment(ref int)"/>. /// </summary> private int _assemblyDirectoryId; public ShadowCopyAnalyzerAssemblyLoader(string baseDirectory = null) { if (baseDirectory != null) { _baseDirectory = baseDirectory; } else { _baseDirectory = Path.Combine(Path.GetTempPath(), "CodeAnalysis", "AnalyzerShadowCopies"); } _shadowCopyDirectoryAndMutex = new Lazy<(string directory, Mutex)>( () => CreateUniqueDirectoryForProcess(), LazyThreadSafetyMode.ExecutionAndPublication); DeleteLeftoverDirectoriesTask = Task.Run((Action)DeleteLeftoverDirectories); } private void DeleteLeftoverDirectories() { // Avoid first chance exception if (!Directory.Exists(_baseDirectory)) return; IEnumerable<string> subDirectories; try { subDirectories = Directory.EnumerateDirectories(_baseDirectory); } catch (DirectoryNotFoundException) { return; } foreach (var subDirectory in subDirectories) { string name = Path.GetFileName(subDirectory).ToLowerInvariant(); Mutex mutex = null; try { // We only want to try deleting the directory if no-one else is currently // using it. That is, if there is no corresponding mutex. if (!Mutex.TryOpenExisting(name, out mutex)) { ClearReadOnlyFlagOnFiles(subDirectory); Directory.Delete(subDirectory, recursive: true); } } catch { // If something goes wrong we will leave it to the next run to clean up. // Just swallow the exception and move on. } finally { if (mutex != null) { mutex.Dispose(); } } } } protected override Assembly LoadImpl(string fullPath) { string assemblyDirectory = CreateUniqueDirectoryForAssembly(); string shadowCopyPath = CopyFileAndResources(fullPath, assemblyDirectory); return base.LoadImpl(shadowCopyPath); } private static string CopyFileAndResources(string fullPath, string assemblyDirectory) { string fileNameWithExtension = Path.GetFileName(fullPath); string shadowCopyPath = Path.Combine(assemblyDirectory, fileNameWithExtension); CopyFile(fullPath, shadowCopyPath); string originalDirectory = Path.GetDirectoryName(fullPath); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithExtension); string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources"; string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll"; foreach (var directory in Directory.EnumerateDirectories(originalDirectory)) { string directoryName = Path.GetFileName(directory); string resourcesPath = Path.Combine(directory, resourcesNameWithExtension); if (File.Exists(resourcesPath)) { string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithExtension); CopyFile(resourcesPath, resourcesShadowCopyPath); } resourcesPath = Path.Combine(directory, resourcesNameWithoutExtension, resourcesNameWithExtension); if (File.Exists(resourcesPath)) { string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithoutExtension, resourcesNameWithExtension); CopyFile(resourcesPath, resourcesShadowCopyPath); } } return shadowCopyPath; } private static void CopyFile(string originalPath, string shadowCopyPath) { var directory = Path.GetDirectoryName(shadowCopyPath); Directory.CreateDirectory(directory); File.Copy(originalPath, shadowCopyPath); ClearReadOnlyFlagOnFile(new FileInfo(shadowCopyPath)); } private static void ClearReadOnlyFlagOnFiles(string directoryPath) { DirectoryInfo directory = new DirectoryInfo(directoryPath); foreach (var file in directory.EnumerateFiles(searchPattern: "*", searchOption: SearchOption.AllDirectories)) { ClearReadOnlyFlagOnFile(file); } } private static void ClearReadOnlyFlagOnFile(FileInfo fileInfo) { try { if (fileInfo.IsReadOnly) { fileInfo.IsReadOnly = false; } } catch { // There are many reasons this could fail. Ignore it and keep going. } } private string CreateUniqueDirectoryForAssembly() { int directoryId = Interlocked.Increment(ref _assemblyDirectoryId); string directory = Path.Combine(_shadowCopyDirectoryAndMutex.Value.directory, directoryId.ToString()); Directory.CreateDirectory(directory); return directory; } private (string directory, Mutex mutex) CreateUniqueDirectoryForProcess() { string guid = Guid.NewGuid().ToString("N").ToLowerInvariant(); string directory = Path.Combine(_baseDirectory, guid); var mutex = new Mutex(initiallyOwned: false, name: guid); Directory.CreateDirectory(directory); return (directory, mutex); } } }
// 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.Reflection; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal sealed class ShadowCopyAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader { /// <summary> /// The base directory for shadow copies. Each instance of /// <see cref="ShadowCopyAnalyzerAssemblyLoader"/> gets its own /// subdirectory under this directory. This is also the starting point /// for scavenge operations. /// </summary> private readonly string _baseDirectory; internal readonly Task DeleteLeftoverDirectoriesTask; /// <summary> /// The directory where this instance of <see cref="ShadowCopyAnalyzerAssemblyLoader"/> /// will shadow-copy assemblies, and the mutex created to mark that the owner of it is still active. /// </summary> private readonly Lazy<(string directory, Mutex)> _shadowCopyDirectoryAndMutex; /// <summary> /// Used to generate unique names for per-assembly directories. Should be updated with <see cref="Interlocked.Increment(ref int)"/>. /// </summary> private int _assemblyDirectoryId; public ShadowCopyAnalyzerAssemblyLoader(string baseDirectory = null) { if (baseDirectory != null) { _baseDirectory = baseDirectory; } else { _baseDirectory = Path.Combine(Path.GetTempPath(), "CodeAnalysis", "AnalyzerShadowCopies"); } _shadowCopyDirectoryAndMutex = new Lazy<(string directory, Mutex)>( () => CreateUniqueDirectoryForProcess(), LazyThreadSafetyMode.ExecutionAndPublication); DeleteLeftoverDirectoriesTask = Task.Run((Action)DeleteLeftoverDirectories); } private void DeleteLeftoverDirectories() { // Avoid first chance exception if (!Directory.Exists(_baseDirectory)) return; IEnumerable<string> subDirectories; try { subDirectories = Directory.EnumerateDirectories(_baseDirectory); } catch (DirectoryNotFoundException) { return; } foreach (var subDirectory in subDirectories) { string name = Path.GetFileName(subDirectory).ToLowerInvariant(); Mutex mutex = null; try { // We only want to try deleting the directory if no-one else is currently // using it. That is, if there is no corresponding mutex. if (!Mutex.TryOpenExisting(name, out mutex)) { ClearReadOnlyFlagOnFiles(subDirectory); Directory.Delete(subDirectory, recursive: true); } } catch { // If something goes wrong we will leave it to the next run to clean up. // Just swallow the exception and move on. } finally { if (mutex != null) { mutex.Dispose(); } } } } #nullable enable protected override string GetPathToLoad(string fullPath) { string assemblyDirectory = CreateUniqueDirectoryForAssembly(); string shadowCopyPath = CopyFileAndResources(fullPath, assemblyDirectory); return shadowCopyPath; } #nullable disable private static string CopyFileAndResources(string fullPath, string assemblyDirectory) { string fileNameWithExtension = Path.GetFileName(fullPath); string shadowCopyPath = Path.Combine(assemblyDirectory, fileNameWithExtension); CopyFile(fullPath, shadowCopyPath); string originalDirectory = Path.GetDirectoryName(fullPath); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithExtension); string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources"; string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll"; foreach (var directory in Directory.EnumerateDirectories(originalDirectory)) { string directoryName = Path.GetFileName(directory); string resourcesPath = Path.Combine(directory, resourcesNameWithExtension); if (File.Exists(resourcesPath)) { string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithExtension); CopyFile(resourcesPath, resourcesShadowCopyPath); } resourcesPath = Path.Combine(directory, resourcesNameWithoutExtension, resourcesNameWithExtension); if (File.Exists(resourcesPath)) { string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithoutExtension, resourcesNameWithExtension); CopyFile(resourcesPath, resourcesShadowCopyPath); } } return shadowCopyPath; } private static void CopyFile(string originalPath, string shadowCopyPath) { var directory = Path.GetDirectoryName(shadowCopyPath); Directory.CreateDirectory(directory); File.Copy(originalPath, shadowCopyPath); ClearReadOnlyFlagOnFile(new FileInfo(shadowCopyPath)); } private static void ClearReadOnlyFlagOnFiles(string directoryPath) { DirectoryInfo directory = new DirectoryInfo(directoryPath); foreach (var file in directory.EnumerateFiles(searchPattern: "*", searchOption: SearchOption.AllDirectories)) { ClearReadOnlyFlagOnFile(file); } } private static void ClearReadOnlyFlagOnFile(FileInfo fileInfo) { try { if (fileInfo.IsReadOnly) { fileInfo.IsReadOnly = false; } } catch { // There are many reasons this could fail. Ignore it and keep going. } } private string CreateUniqueDirectoryForAssembly() { int directoryId = Interlocked.Increment(ref _assemblyDirectoryId); string directory = Path.Combine(_shadowCopyDirectoryAndMutex.Value.directory, directoryId.ToString()); Directory.CreateDirectory(directory); return directory; } private (string directory, Mutex mutex) CreateUniqueDirectoryForProcess() { string guid = Guid.NewGuid().ToString("N").ToLowerInvariant(); string directory = Path.Combine(_baseDirectory, guid); var mutex = new Mutex(initiallyOwned: false, name: guid); Directory.CreateDirectory(directory); return (directory, mutex); } } }
1